123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- package wsrpc
- //go:generate folder2go client wsrpcAssets
- import (
- "net/http"
- "strings"
- "dev.hexasoftware.com/stdio/wsrpc/wsrpcAssets" // embed assets
- "golang.org/x/net/websocket"
- )
- // Handler wsrpc.Handler
- type Handler struct {
- wsHandler http.Handler
- prefix string
- }
- func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- // Get relative path
- if h.prefix == "" {
- server := r.Context().Value(http.ServerContextKey).(*http.Server)
- mux, ok := server.Handler.(*http.ServeMux)
- if ok {
- _, h.prefix = mux.Handler(r)
- }
- }
- urlPath := strings.TrimPrefix(r.URL.String(), h.prefix)
- switch urlPath {
- case "ws", "wsrpc":
- h.wsHandler.ServeHTTP(w, r)
- case "cli.js", "wsrpc.js": // Serve client JS file
- w.Header().Set("Content-type", "application/javascript")
- w.WriteHeader(200)
- w.Write(wsrpcAssets.Data["wsrpc.js"])
- default:
- w.WriteHeader(http.StatusNotFound)
- w.Write([]byte(http.StatusText(http.StatusNotFound)))
- }
- }
- // New create a new WSRpc handler
- func New(WSRPC Func) *Handler {
- return &Handler{
- wsHandler: websocket.Handler(createCliHandler(WSRPC)),
- }
- }
- // Func for wsrpc
- type Func func(*ClientCtx)
- // Create a client websocket handler on connection
- func createCliHandler(handler Func) websocket.Handler {
- // Move this to clientCTX handler
- return func(ws *websocket.Conn) {
- cli := NewClient(ws)
- go handler(cli) // Paralell launch a client initiator
- cli.Process() // blocks
- }
- }
|