Integrate third-party applications

Beego supports to integrate third-party application, you can customize http.Handler as follows:

  1. beego.Handler("/chat/:info(.*)", sockjs.NewHandler("/chat", opt, YouHandlerFunc))

sockjshandler implemented interface http.Handler.

Beego has an example for supporting echo app of sockjs, here is the code:

  1. package main
  2. import (
  3. "log"
  4. "time"
  5. "gopkg.in/igm/sockjs-go.v2/sockjs"
  6. )
  7. func LiveUpdate(session sockjs.Session) {
  8. var closedSession = make(chan struct{})
  9. reader := make(chan string)
  10. go func() {
  11. for {
  12. reader <- "echo"
  13. time.Sleep(time.Second)
  14. }
  15. }()
  16. go func() {
  17. for {
  18. select {
  19. case <-closedSession:
  20. return
  21. case msg := <-reader:
  22. if err := session.Send(msg); err != nil {
  23. return
  24. }
  25. }
  26. }
  27. }()
  28. for {
  29. if _, err := session.Recv(); err == nil {
  30. continue
  31. }
  32. break
  33. }
  34. close(closedSession)
  35. log.Println("sockjs session closed")
  36. }
  37. type MainController struct {
  38. beego.Controller
  39. }
  40. func (m *MainController) Get() {
  41. m.TplNames = "index.html"
  42. }
  43. func main() {
  44. beego.Router("/", &MainController{})
  45. beego.Handler("/chat/:info(.*)", sockjs.NewHandler("/chat", sockjs.DefaultOptions, YouHandlerFunc))
  46. beego.Run()
  47. }

JS code:

  1. if (!window.location.origin) { // Some browsers (mainly IE) do not have this property, so we need to build it manually...
  2. window.location.origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? (':' + window.location.port) : '');
  3. }
  4. var recInterval = null;
  5. var socket = null;
  6. var new_conn = function() {
  7. socket = new SockJS('/live_update', null, {
  8. 'protocols_whitelist': ['websocket', 'xdr-streaming', 'xhr-streaming',
  9. 'iframe-eventsource', 'iframe-htmlfile',
  10. 'xdr-polling', 'xhr-polling', 'iframe-xhr-polling',
  11. 'jsonp-polling'
  12. ]
  13. });
  14. clearInterval(recInterval);
  15. socket.onclose = function() {
  16. socket = null;
  17. recInterval = setInterval(function() {
  18. new_conn();
  19. }, 2000);
  20. };
  21. socket.onmessage = function(e) {
  22. document.getElementById("output").value += e.data +"\n";
  23. };
  24. };
  25. (function () {
  26. new_conn();
  27. })();

The above example implemented a simple echo app for sockjs, and you can use http.Handler for more extensions.