forked from harlow/go-middleware-example
/
main.go
85 lines (69 loc) · 2.06 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
package main
import (
"expvar"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/harlow/go-middleware-context/requestid"
"github.com/harlow/go-middleware-context/userip"
"github.com/harlow/httpctx"
"github.com/paulbellamy/ratecounter"
"golang.org/x/net/context"
)
var (
counter *ratecounter.RateCounter
hitsperminute = expvar.NewInt("hits_per_minute")
)
type Server struct {
context.Context
httpctx.Handler
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.Handler.ServeHTTP(s.Context, w, r)
}
func requestIDMiddleware(next httpctx.Handler) httpctx.Handler {
return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
if reqID, ok := requestid.FromRequest(r); ok == nil {
ctx = requestid.NewContext(ctx, reqID)
}
next.ServeHTTP(ctx, w, r)
})
}
func requestCtrMiddleware(next httpctx.Handler) httpctx.Handler {
return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
counter.Incr(1)
hitsperminute.Set(counter.Rate())
next.ServeHTTP(ctx, w, r)
})
}
func userIPMiddleware(next httpctx.Handler) httpctx.Handler {
return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
if userIP, ok := userip.FromRequest(r); ok == nil {
ctx = userip.NewContext(ctx, userIP)
}
next.ServeHTTP(ctx, w, r)
})
}
func requestHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
reqID, _ := requestid.FromContext(ctx)
userIP, _ := userip.FromContext(ctx)
fmt.Fprintf(w, "Hello request: %s, from %s\n", reqID, userIP)
}
func main() {
counter = ratecounter.NewRateCounter(1 * time.Minute)
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
var handler httpctx.Handler
handler = httpctx.HandlerFunc(requestHandler)
handler = userIPMiddleware(handler)
handler = requestIDMiddleware(handler)
handler = requestCtrMiddleware(handler)
ctx := context.Background()
svc := &Server{ctx, handler}
http.HandleFunc("/", svc.ServeHTTP)
log.Fatal(http.ListenAndServe(":"+port, nil))
}