-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhandler.go
69 lines (59 loc) · 1.83 KB
/
handler.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
package vangoh
import (
"net/http"
)
/*
Protect a `http.Handler` from unauthenticated requests. The wrapped handler
will only be called if the request contains a valid Authorization header.
Example:
func main() {
// Create a new Vangoh instance.
vg := vangoh.New()
// Assuming the endpoint to be protected is called 'baseHandler'.
protectedHandler := vg.Handler(unprotectedHandler)
// Works just like any other `http.Handler`.
http.ListenAndServe("0.0.0.0:3000", protectedHandler)
}
*/
func (vg *Vangoh) Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Hand the request off to be authenticated. If an error is encountered,
// err will be non-null, but AuthenticateRequest will take care of writing
// the appropriate http response on the ResponseWriter
authErr := vg.AuthenticateRequest(r)
if authErr != nil {
authErr.WriteResponse(w, vg.GetDebug())
return
}
h.ServeHTTP(w, r)
})
}
/*
Implements the `negroni.Handler` interface, for use as a middleware.
Example:
func main() {
mux := http.NewServeMux()
// Create a new Vangoh instance.
vg := vangoh.New()
// Create a new Negroni instance, with the standard Recovery and Logger
// middlewares.
n := negroni.New(
negroni.NewRecovery(),
negroni.NewLogger(),
negroni.HandlerFunc(vg.NegroniHandler))
// Run the app.
n.UseHandler(mux)
n.Run(":3000")
}
*/
func (vg *Vangoh) NegroniHandler(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
// Hand the request off to be authenticated. If an error is encountered, err
// will be non-null, but AuthenticateRequest will take care of writing the
// appropriate http response on the ResponseWriter
authErr := vg.AuthenticateRequest(r)
if authErr != nil {
authErr.WriteResponse(w, vg.GetDebug())
return
}
next(w, r)
}