-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
87 lines (79 loc) · 2 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
"sync"
)
type Server struct {
once sync.Once
mux *http.ServeMux
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.once.Do(func() {
if s.mux == nil {
s.mux = http.NewServeMux()
}
// foo requires a login and a special header
s.mux.HandleFunc("/foo", s.middlewareRequireToken(s.middlewareRequireHeader(s.handleFoo(), "SOME-HEADER")))
// bar requires only a login
s.mux.HandleFunc("/bar", s.middlewareRequireToken(s.handleBar()))
s.mux.HandleFunc("/login", s.handleLogin())
})
s.mux.ServeHTTP(w, r)
}
func (s *Server) handleFoo() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := json.NewEncoder(w).Encode(&Foo{
Foo: 123,
})
if err != nil {
log.Println(err)
}
}
}
func (s *Server) handleBar() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := json.NewEncoder(w).Encode(&Bar{
Bar: "tiki",
})
if err != nil {
log.Println(err)
}
}
}
func (s *Server) handleLogin() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
// this is the worst possible way to check auth
if ok && user == "tom" && pass == "password1" {
w.Header().Set("TOKEN", "YOU'RE SPECIAL")
return
}
http.NotFound(w, r)
}
}
func (s *Server) middlewareRequireToken(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// this is also the worst possible auth
if v := r.Header.Get("TOKEN"); !strings.EqualFold(v, "YOU'RE SPECIAL") {
w.WriteHeader(http.StatusForbidden)
return
}
next(w, r)
}
}
func (s *Server) middlewareRequireHeader(next http.HandlerFunc, h string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if v := r.Header.Get(h); v == "" {
w.WriteHeader(http.StatusBadRequest)
_, err:=w.Write([]byte("missing header " + h))
if err != nil {
log.Println(err)
}
return
}
next(w, r)
}
}