...
1 package httprp
2
3 import (
4 "context"
5 "net/http"
6 "net/http/httputil"
7 "net/url"
8 )
9
10
11
12
13 type RequestFunc func(context.Context, *http.Request) context.Context
14
15
16 type Server struct {
17 proxy http.Handler
18 before []RequestFunc
19 errorEncoder func(w http.ResponseWriter, err error)
20 }
21
22
23
24
25
26 func NewServer(
27 baseURL *url.URL,
28 options ...ServerOption,
29 ) *Server {
30 s := &Server{
31 proxy: httputil.NewSingleHostReverseProxy(baseURL),
32 }
33 for _, option := range options {
34 option(s)
35 }
36 return s
37 }
38
39
40 type ServerOption func(*Server)
41
42
43
44 func ServerBefore(before ...RequestFunc) ServerOption {
45 return func(s *Server) { s.before = append(s.before, before...) }
46 }
47
48
49 func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
50 ctx := r.Context()
51
52 for _, f := range s.before {
53 ctx = f(ctx, r)
54 }
55
56 s.proxy.ServeHTTP(w, r)
57 }
58
View as plain text