2015-03-04 00:49:45 +08:00
|
|
|
// Package websockets implements a WebSocket server by executing
|
|
|
|
// a command and piping its input and output through the WebSocket
|
|
|
|
// connection.
|
|
|
|
package websockets
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/mholt/caddy/middleware"
|
|
|
|
"golang.org/x/net/websocket"
|
|
|
|
)
|
|
|
|
|
2015-03-04 08:36:18 +08:00
|
|
|
type (
|
|
|
|
// WebSockets is a type that holds configuration for the
|
|
|
|
// websocket middleware generally, like a list of all the
|
|
|
|
// websocket endpoints.
|
|
|
|
WebSockets struct {
|
2015-03-20 13:52:56 +08:00
|
|
|
// Next is the next HTTP handler in the chain for when the path doesn't match
|
2015-04-03 13:30:54 +08:00
|
|
|
Next middleware.Handler
|
2015-03-20 13:52:56 +08:00
|
|
|
|
2015-03-04 09:39:38 +08:00
|
|
|
// Sockets holds all the web socket endpoint configurations
|
2015-05-05 01:49:49 +08:00
|
|
|
Sockets []Config
|
2015-03-04 08:36:18 +08:00
|
|
|
}
|
|
|
|
|
2015-05-25 09:04:03 +08:00
|
|
|
// Config holds the configuration for a single websocket
|
2015-03-20 13:52:56 +08:00
|
|
|
// endpoint which may serve multiple websocket connections.
|
2015-05-05 01:49:49 +08:00
|
|
|
Config struct {
|
2015-03-04 08:36:18 +08:00
|
|
|
Path string
|
|
|
|
Command string
|
|
|
|
Arguments []string
|
2015-03-20 13:52:56 +08:00
|
|
|
Respawn bool // TODO: Not used, but parser supports it until we decide on it
|
2015-03-04 08:36:18 +08:00
|
|
|
}
|
|
|
|
)
|
2015-03-04 00:49:45 +08:00
|
|
|
|
2015-03-04 08:36:18 +08:00
|
|
|
// ServeHTTP converts the HTTP request to a WebSocket connection and serves it up.
|
2015-03-29 06:56:33 +08:00
|
|
|
func (ws WebSockets) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
2015-03-04 08:36:18 +08:00
|
|
|
for _, sockconfig := range ws.Sockets {
|
|
|
|
if middleware.Path(r.URL.Path).Matches(sockconfig.Path) {
|
|
|
|
socket := WebSocket{
|
2015-05-05 01:49:49 +08:00
|
|
|
Config: sockconfig,
|
|
|
|
Request: r,
|
2015-03-04 08:36:18 +08:00
|
|
|
}
|
2015-03-04 00:49:45 +08:00
|
|
|
websocket.Handler(socket.Handle).ServeHTTP(w, r)
|
2015-03-29 06:56:33 +08:00
|
|
|
return 0, nil
|
2015-03-04 00:49:45 +08:00
|
|
|
}
|
|
|
|
}
|
2015-03-20 13:52:56 +08:00
|
|
|
|
|
|
|
// Didn't match a websocket path, so pass-thru
|
2015-04-03 13:30:54 +08:00
|
|
|
return ws.Next.ServeHTTP(w, r)
|
2015-03-04 00:49:45 +08:00
|
|
|
}
|
|
|
|
|
2015-03-04 09:39:38 +08:00
|
|
|
var (
|
2015-05-25 09:04:03 +08:00
|
|
|
// GatewayInterface is the dialect of CGI being used by the server
|
|
|
|
// to communicate with the script. See CGI spec, 4.1.4
|
2015-03-04 09:39:38 +08:00
|
|
|
GatewayInterface string
|
|
|
|
|
2015-05-25 09:04:03 +08:00
|
|
|
// ServerSoftware is the name and version of the information server
|
|
|
|
// software making the CGI request. See CGI spec, 4.1.17
|
2015-03-04 09:39:38 +08:00
|
|
|
ServerSoftware string
|
|
|
|
)
|