wsrpc.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. h.wsHandler.ServeHTTP(w, r)
  28. case "cli.js": // Serve client JS file
  29. w.Header().Set("Content-type", "application/javascript")
  30. w.WriteHeader(200)
  31. w.Write(wsrpcAssets.Data["wsrpc.js"])
  32. default:
  33. w.WriteHeader(http.StatusNotFound)
  34. w.Write([]byte(http.StatusText(http.StatusNotFound)))
  35. }
  36. }
  37. // New create a new WSRpc handler
  38. func New(WSRPC Func) *Handler {
  39. return &Handler{
  40. wsHandler: websocket.Handler(createCliHandler(WSRPC)),
  41. }
  42. }
  43. // Func for wsrpc
  44. type Func func(*ClientCtx)
  45. // Create a client websocket handler on connection
  46. func createCliHandler(handler Func) websocket.Handler {
  47. return func(ws *websocket.Conn) {
  48. ch := NewHandler("main", ws)
  49. go handler(ch)
  50. for {
  51. var data = CallObj{}
  52. err := websocket.JSON.Receive(ws, &data)
  53. if err != nil {
  54. log.Println("Error: ", err)
  55. return
  56. }
  57. ch.Process(data)
  58. }
  59. }
  60. }
  61. // RegisterTo register both js and websocket in the servermux
  62. /*func RegisterTo(server ServerContext, handler HandleFunc) {
  63. server.Handle("/wsrpc", websocket.Handler(createCliHandler(handler)))
  64. server.HandleFunc("/wsrpc/client.js", wsrpcjsFunc)
  65. }
  66. // Handler we can attatch this to http.Server
  67. func Handler(handler HandleFunc) http.Handler {
  68. mux := http.NewServeMux()
  69. RegisterTo(mux, handler)
  70. // When we receive a connection
  71. return mux
  72. }*/