This repository has been archived by the owner on Mar 1, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
57 lines (50 loc) · 1.41 KB
/
server.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
package main
import (
"fmt"
"log"
"net/http"
"strings"
"github.com/gorilla/websocket"
)
// ASGIHandler handels all incomming requests
func asgiHandler(w http.ResponseWriter, req *http.Request) {
var err error
if websocket.IsWebSocketUpgrade(req) {
if err = asgiWebsocketHandler(w, req); err != nil {
log.Printf("%s", err)
}
return
}
err = asgiHTTPHandler(w, req)
if err != nil {
handleError(w, err.Error(), http.StatusInternalServerError)
}
}
func handleError(w http.ResponseWriter, m string, status int) {
log.Printf("Error: %s", m)
if !debug {
m = "Internal error."
} else {
m = fmt.Sprintf("%d: Error: %s.", status, m)
}
http.Error(w, m, status)
}
// Writes an output to the log for each incomming request.
func httpLogger(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func startHTTPServer(listen string, statics []string) {
for _, static := range statics {
paths := strings.SplitN(static, ":", 2)
if len(paths) != 2 {
log.Fatalf("Invalid argument for --static \"%s\"", static)
}
http.Handle(paths[0], http.StripPrefix(paths[0], http.FileServer(http.Dir(paths[1]))))
}
http.HandleFunc("/", asgiHandler)
log.Printf("Start webserver to listen on %s", listen)
log.Fatal(http.ListenAndServe(listen, httpLogger(http.DefaultServeMux)))
}