-
Notifications
You must be signed in to change notification settings - Fork 7
/
with_key.go
85 lines (76 loc) · 2.02 KB
/
with_key.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 (
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/stampede"
)
// Example 1: Make two parallel requests:
// First request in first client:
// GET http://localhost:3333/me
// Authorization: Bar
//
// Second request in second client:
// GET http://localhost:3333/me
// Authorization: Bar
//
// -> Result of both queries in one time:
// HTTP/1.1 200 OK
// Content-Length: 14
// Content-Type: text/plain; charset=utf-8
//
// Bearer BarTone
//
// Response code: 200 (OK); Time: 1ms; Content length: 14 bytes
//
// ---------------------------------------------------------------
//
// Example 2: Make two parallel requests:
// First request in first client:
// GET http://localhost:3333/me
// Authorization: Bar
//
// Second request in second client:
// GET http://localhost:3333/me
// Authorization: Foo
//
// -> Result of first:
// HTTP/1.1 200 OK
// Content-Length: 14
// Content-Type: text/plain; charset=utf-8
//
// Bearer Bar
//
// Response code: 200 (OK); Time: 1ms; Content length: 14 bytes
//
// -> Result of second:
// HTTP/1.1 200 OK
// Content-Length: 14
// Content-Type: text/plain; charset=utf-8
//
// Bearer Foo
//
// Response code: 200 (OK); Time: 1ms; Content length: 14 bytes
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("index"))
})
// Include anything user specific, e.g. Authorization Token
customKeyFunc := func(r *http.Request) uint64 {
token := r.Header.Get("Authorization")
return stampede.StringToHash(r.Method, strings.ToLower(strings.ToLower(token)))
}
cached := stampede.HandlerWithKey(512, 1*time.Second, customKeyFunc)
r.With(cached).Get("/me", func(w http.ResponseWriter, r *http.Request) {
// processing..
time.Sleep(3 * time.Second)
w.WriteHeader(200)
w.Write([]byte(r.Header.Get("Authorization")))
})
http.ListenAndServe(":3333", r)
}