forked from micro/micro
/
handler.go
108 lines (92 loc) · 2.46 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package server
import (
"context"
"net/http"
"github.com/tickoalcantara12/micro/v3/service/api"
"github.com/tickoalcantara12/micro/v3/service/api/handler"
"github.com/tickoalcantara12/micro/v3/service/api/router"
"github.com/tickoalcantara12/micro/v3/service/client"
"github.com/tickoalcantara12/micro/v3/service/errors"
aapi "github.com/tickoalcantara12/micro/v3/service/api/handler/api"
"github.com/tickoalcantara12/micro/v3/service/api/handler/event"
ahttp "github.com/tickoalcantara12/micro/v3/service/api/handler/http"
"github.com/tickoalcantara12/micro/v3/service/api/handler/rpc"
"github.com/tickoalcantara12/micro/v3/service/api/handler/web"
)
type metaHandler struct {
c client.Client
r router.Router
ns string
}
var (
// built in handlers
handlers = map[string]handler.Handler{
"rpc": rpc.NewHandler(),
"web": web.NewHandler(),
"http": ahttp.NewHandler(),
"event": event.NewHandler(),
"api": aapi.NewHandler(),
}
)
// Register a handler
func Register(handler string, hd handler.Handler) {
handlers[handler] = hd
}
// serverContext
type serverContext struct {
context.Context
domain string
client client.Client
service *api.Service
}
func (c *serverContext) Service() *api.Service {
return c.service
}
func (c *serverContext) Client() client.Client {
return c.client
}
func (c *serverContext) Domain() string {
return c.domain
}
func (m *metaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
service, err := m.r.Route(r)
if err != nil {
er := errors.InternalServerError(m.ns, err.Error())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
w.Write([]byte(er.Error()))
return
}
// inject service into context
ctx := r.Context()
// create a new server context
srvContext := &serverContext{
Context: ctx,
domain: m.ns,
client: m.c,
service: service,
}
// clone request with new context
req := r.Clone(srvContext)
// get the necessary handler
hd := service.Endpoint.Handler
// retrieve the handler for the request
if len(hd) == 0 {
hd = "rpc"
}
hdr, ok := handlers[hd]
if !ok {
// use the catch all rpc handler
hdr = handlers["rpc"]
}
// serve the request
hdr.ServeHTTP(w, req)
}
// Meta is a http.Handler that routes based on endpoint metadata
func Meta(c client.Client, r router.Router, ns string) http.Handler {
return &metaHandler{
c: c,
r: r,
ns: ns,
}
}