-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
64 lines (57 loc) · 2.33 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
package lungo
import (
"context"
"net/http"
)
type (
// Handler is the generic interface for responding to an HTTP request.
//
// ServeHTTP should write reply headers and data to the ResponseWriter
// and then return. Returning signals that the request is finished; it
// is not valid to use the ResponseWriter or read from the
// Request.Body after or concurrently with the completion of the
// ServeHTTP call.
//
// Depending on the HTTP client software, HTTP protocol version, and
// any intermediaries between the client and the Go server, it may not
// be possible to read from the Request.Body after writing to the
// ResponseWriter. Cautious handlers should read the Request.Body
// first, and then reply.
//
// Except for reading the body, handlers should not modify the
// provided Request.
//
// If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
// that the effect of the panic was isolated to the active request.
// It recovers the panic, logs a stack trace to the server error log,
// and either closes the network connection or sends an HTTP/2
// RST_STREAM, depending on the HTTP protocol. To abort a handler so
// the client sees an interrupted response but the server doesn't log
// an error, panic with the value ErrAbortHandler.
Handler interface {
ServeHTTP(c *Context) error
}
// Middleware is a function which receives an Handler and returns another Handler.
Middleware func(Handler) Handler
// HandlerFunc is the type of an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
HandlerFunc func(c *Context) error
)
// ContextKey defines the key to retrieve the Lungo context
// context from the request context
var ContextKey = &struct{}{}
// ServeHTTP implements the Handler interface for
// HandlerFunc by simply returning the function call
// with the provided context
func (h HandlerFunc) ServeHTTP(c *Context) error { return h(c) }
// WithContext is an adapter to allow the usage of http.Handler
// with the context based API provided by Lungo
func WithContext(handler http.Handler) HandlerFunc {
return HandlerFunc(func(c *Context) error {
ctx := context.WithValue(c.Request.Context(), ContextKey, c)
handler.ServeHTTP(c.Response, c.Request.WithContext(ctx))
return nil
})
}