This repository has been archived by the owner on Jul 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
httphandler.go
72 lines (60 loc) · 1.98 KB
/
httphandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"fmt"
"net/http"
"github.com/apex/log"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
)
// HTTPHandler - handles incoming HTTP requests
type HTTPHandler struct {
Router *mux.Router
}
// handleIndex - Handles clients which want to receive the index page
func handleIndex(mel *Melodious, w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World! You should really use a proper Melodious client instead of opening this page\n")
}
// handleConnect - Handles clients which want to connect to Melodious
func handleConnect(mel *Melodious, w http.ResponseWriter, r *http.Request) {
originChecker := func(*http.Request) bool { return true }
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: originChecker,
}
header := http.Header{}
header.Add("Sec-WebSocket-Protocol", "melodious")
if contains(websocket.Subprotocols(r), "melodious") {
conn, err := upgrader.Upgrade(w, r, header)
if err != nil {
log.WithFields(log.Fields{"err": err, "addr": r.RemoteAddr, "path": r.URL.Path}).Error("cannot upgrade to websocket")
} else {
go handleConnection(mel, conn)
}
} else {
w.WriteHeader(http.StatusBadRequest)
}
}
// NewHTTPHandler - creates a new HTTPHandler xD
func NewHTTPHandler(mel *Melodious) *HTTPHandler {
router := mux.NewRouter()
wrap := func(mel *Melodious, f func(*Melodious, http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
f(mel, w, r)
}
}
router.HandleFunc("/", wrap(mel, handleIndex))
router.HandleFunc("/connect", wrap(mel, handleConnect))
return &HTTPHandler{
Router: router,
}
}
// ServeHTTP - http.ListenAndServe invokes this on incoming request
func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var err error
defer log.WithFields(log.Fields{
"addr": r.RemoteAddr,
"path": r.URL.Path,
}).Trace("serving http").Stop(&err)
h.Router.ServeHTTP(w, r)
}