-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
86 lines (67 loc) · 1.74 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"go.mongodb.org/mongo-driver/bson"
)
func loggingHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
next.ServeHTTP(w, r)
t2 := time.Now()
log.Printf("[%s] %q %v\n", r.Method, r.URL.String(), t2.Sub(t1))
}
return http.HandlerFunc(fn)
}
func recoverHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("panic: %+v", err)
http.Error(w, http.StatusText(500), 500)
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
// fmt.Fprintf(w, "You are on the about page.")
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Can't read body", http.StatusBadRequest)
return
}
var object bson.M
json.Unmarshal(body, &object)
log.Print(object["tal"].(int64))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome!")
}
type Constructor func(http.Handler) http.Handler
type Chain struct {
constructors []Constructor
}
func New(constructors ...Constructor) Chain {
return Chain{append(([]Constructor)(nil), constructors...)}
}
func (c Chain) Then(h http.Handler) http.Handler {
if h == nil {
h = http.DefaultServeMux
}
for i := range c.constructors {
h = c.constructors[len(c.constructors)-1-i](h)
}
return h
}
func main() {
commonHandlers := New(loggingHandler, recoverHandler)
http.Handle("/", commonHandlers.Then(http.HandlerFunc(indexHandler)))
http.Handle("/about", commonHandlers.Then(http.HandlerFunc(aboutHandler)))
http.ListenAndServe(":8080", nil)
}