-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
52 lines (45 loc) · 968 Bytes
/
server.go
File metadata and controls
52 lines (45 loc) · 968 Bytes
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
package spartan
import (
"context"
"encoding/json"
"log"
"net"
"net/http"
"strings"
)
func NewServer(ctx context.Context, raw []byte) *http.Server {
return &http.Server{
Addr: ":8000",
BaseContext: func(net.Listener) context.Context {
return ctx
},
Handler: newHandler(raw),
}
}
type Handler struct {
Routes map[string]string `json:"routes"`
}
func newHandler(raw []byte) http.Handler {
var conf Handler
if err := json.Unmarshal(raw, &conf); err != nil {
panic(err)
}
return conf
}
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
p := req.URL.Path
if len(p) > 1 && strings.HasSuffix(p, "/") {
p = p[:len(p)-1]
}
dst := h.Routes[p]
if dst == "" {
log.Printf("unknown path: %s", p)
dst = h.Routes["/"]
}
if dst == "" {
w.WriteHeader(http.StatusNotImplemented)
return
}
log.Printf("[%d] %s -> %s", http.StatusTemporaryRedirect, p, dst)
http.Redirect(w, req, dst, http.StatusTemporaryRedirect)
}