wsrpc.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package wsrpc
  2. //go:generate folder2go client wsrpcAssets
  3. import (
  4. "log"
  5. "net/http"
  6. "strings"
  7. "dev.hexasoftware.com/stdio/wsrpc/wsrpcAssets" // embed assets
  8. "golang.org/x/net/websocket"
  9. )
  10. // Handler wsrpc.Handler
  11. type Handler struct {
  12. wsHandler http.Handler
  13. prefix string
  14. }
  15. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  16. // Get relative path
  17. if h.prefix == "" {
  18. server := r.Context().Value(http.ServerContextKey).(*http.Server)
  19. mux, ok := server.Handler.(*http.ServeMux)
  20. if ok {
  21. _, h.prefix = mux.Handler(r)
  22. }
  23. }
  24. urlPath := strings.TrimPrefix(r.URL.String(), h.prefix)
  25. switch urlPath {
  26. case "ws", "wsrpc":
  27. log.Println("Provide ws connection")
  28. h.wsHandler.ServeHTTP(w, r)
  29. case "cli.js": // Serve client JS file
  30. log.Println("Sending cli")
  31. w.Header().Set("Content-type", "application/javascript")
  32. w.WriteHeader(200)
  33. w.Write(wsrpcAssets.Data["wsrpc.js"])
  34. default:
  35. w.WriteHeader(http.StatusNotFound)
  36. w.Write([]byte(http.StatusText(http.StatusNotFound)))
  37. }
  38. }
  39. // New create a new WSRpc handler
  40. func New(WSRPC Func) *Handler {
  41. return &Handler{
  42. wsHandler: websocket.Handler(createCliHandler(WSRPC)),
  43. }
  44. }
  45. // Func for wsrpc
  46. type Func func(*ClientCtx)
  47. // Create a client websocket handler on connection
  48. func createCliHandler(handler Func) websocket.Handler {
  49. return func(ws *websocket.Conn) {
  50. ch := NewHandler("main", ws)
  51. go handler(ch)
  52. for {
  53. var data = CallObj{}
  54. err := websocket.JSON.Receive(ws, &data)
  55. if err != nil {
  56. log.Println("Error: ", err)
  57. return
  58. }
  59. ch.Process(data)
  60. }
  61. }
  62. }
  63. // RegisterTo register both js and websocket in the servermux
  64. /*func RegisterTo(server ServerContext, handler HandleFunc) {
  65. server.Handle("/wsrpc", websocket.Handler(createCliHandler(handler)))
  66. server.HandleFunc("/wsrpc/client.js", wsrpcjsFunc)
  67. }
  68. // Handler we can attatch this to http.Server
  69. func Handler(handler HandleFunc) http.Handler {
  70. mux := http.NewServeMux()
  71. RegisterTo(mux, handler)
  72. // When we receive a connection
  73. return mux
  74. }*/