forked from micro/micro
/
api.go
300 lines (270 loc) · 7.4 KB
/
api.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// Package api is an API Gateway
package api
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/micro/cli"
ahandler "github.com/micro/go-api/handler"
aapi "github.com/micro/go-api/handler/api"
"github.com/micro/go-api/handler/event"
ahttp "github.com/micro/go-api/handler/http"
arpc "github.com/micro/go-api/handler/rpc"
"github.com/micro/go-api/handler/web"
"github.com/micro/go-api/resolver"
"github.com/micro/go-api/resolver/grpc"
"github.com/micro/go-api/resolver/host"
rrmicro "github.com/micro/go-api/resolver/micro"
"github.com/micro/go-api/resolver/path"
"github.com/micro/go-api/router"
"github.com/micro/go-api/server"
"github.com/micro/go-log"
"github.com/micro/go-micro"
"github.com/micro/micro/internal/handler"
"github.com/micro/micro/internal/helper"
"github.com/micro/micro/internal/stats"
"github.com/micro/micro/plugin"
)
var (
Name = "go.micro.api"
Address = ":8080"
Handler = "meta"
Resolver = "micro"
RPCPath = "/rpc"
APIPath = "/"
ProxyPath = "/{service:[a-zA-Z0-9]+}"
Namespace = "go.micro.api"
HeaderPrefix = "X-Micro-"
CORS = map[string]bool{"*": true}
)
type srv struct {
*mux.Router
}
func (s *srv) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); CORS[origin] {
w.Header().Set("Access-Control-Allow-Origin", origin)
} else if len(origin) > 0 && CORS["*"] {
w.Header().Set("Access-Control-Allow-Origin", origin)
}
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PATCH, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == "OPTIONS" {
return
}
s.Router.ServeHTTP(w, r)
}
func run(ctx *cli.Context) {
if len(ctx.GlobalString("server_name")) > 0 {
Name = ctx.GlobalString("server_name")
}
if len(ctx.String("address")) > 0 {
Address = ctx.String("address")
}
if len(ctx.String("handler")) > 0 {
Handler = ctx.String("handler")
}
if len(ctx.String("namespace")) > 0 {
Namespace = ctx.String("namespace")
}
if len(ctx.String("resolver")) > 0 {
Resolver = ctx.String("resolver")
}
if len(ctx.String("cors")) > 0 {
origins := make(map[string]bool)
for _, origin := range strings.Split(ctx.String("cors"), ",") {
origins[origin] = true
}
CORS = origins
}
// Init plugins
for _, p := range Plugins() {
p.Init(ctx)
}
// Init API
var opts []server.Option
if ctx.GlobalBool("enable_acme") {
hosts := helper.ACMEHosts(ctx)
opts = append(opts, server.EnableACME(true))
opts = append(opts, server.ACMEHosts(hosts...))
} else if ctx.GlobalBool("enable_tls") {
config, err := helper.TLSConfig(ctx)
if err != nil {
fmt.Println(err.Error())
return
}
opts = append(opts, server.EnableTLS(true))
opts = append(opts, server.TLSConfig(config))
}
// create the router
r := mux.NewRouter()
s := &srv{r}
var h http.Handler = s
if ctx.GlobalBool("enable_stats") {
st := stats.New()
r.HandleFunc("/stats", st.StatsHandler)
h = st.ServeHTTP(s)
st.Start()
defer st.Stop()
}
// initialise service
service := micro.NewService(
micro.Name(Name),
micro.RegisterTTL(
time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
),
micro.RegisterInterval(
time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
),
)
// register rpc handler
log.Logf("Registering RPC Handler at %s", RPCPath)
r.HandleFunc(RPCPath, handler.RPC)
// resolver options
ropts := []resolver.Option{
resolver.WithNamespace(Namespace),
resolver.WithHandler(Handler),
}
// default resolver
rr := rrmicro.NewResolver(ropts...)
switch Resolver {
case "host":
rr = host.NewResolver(ropts...)
case "path":
rr = path.NewResolver(ropts...)
case "grpc":
rr = grpc.NewResolver(ropts...)
}
switch Handler {
case "rpc":
log.Logf("Registering API RPC Handler at %s", APIPath)
rt := router.NewRouter(
router.WithNamespace(Namespace),
router.WithHandler(arpc.Handler),
router.WithResolver(rr),
)
rp := arpc.NewHandler(
ahandler.WithNamespace(Namespace),
ahandler.WithRouter(rt),
ahandler.WithService(service),
)
r.PathPrefix(APIPath).Handler(rp)
case "api":
log.Logf("Registering API Request Handler at %s", APIPath)
rt := router.NewRouter(
router.WithNamespace(Namespace),
router.WithHandler(aapi.Handler),
router.WithResolver(rr),
)
ap := aapi.NewHandler(
ahandler.WithNamespace(Namespace),
ahandler.WithRouter(rt),
ahandler.WithService(service),
)
r.PathPrefix(APIPath).Handler(ap)
case "event":
log.Logf("Registering API Event Handler at %s", APIPath)
rt := router.NewRouter(
router.WithNamespace(Namespace),
router.WithHandler(event.Handler),
router.WithResolver(rr),
)
ev := event.NewHandler(ahandler.WithNamespace(Namespace), ahandler.WithRouter(rt))
r.PathPrefix(APIPath).Handler(ev)
case "http", "proxy":
log.Logf("Registering API HTTP Handler at %s", ProxyPath)
rt := router.NewRouter(
router.WithNamespace(Namespace),
router.WithHandler(ahttp.Handler),
router.WithResolver(rr),
)
ht := ahttp.NewHandler(
ahandler.WithNamespace(Namespace),
ahandler.WithRouter(rt),
ahandler.WithService(service),
)
r.PathPrefix(ProxyPath).Handler(ht)
case "web":
log.Logf("Registering API Web Handler at %s", APIPath)
rt := router.NewRouter(
router.WithNamespace(Namespace),
router.WithHandler(web.Handler),
router.WithResolver(rr),
)
w := web.NewHandler(
ahandler.WithNamespace(Namespace),
ahandler.WithRouter(rt),
ahandler.WithService(service),
)
r.PathPrefix(APIPath).Handler(w)
default:
log.Logf("Registering API Default Handler at %s", APIPath)
r.PathPrefix(APIPath).Handler(handler.Meta(Namespace))
}
// reverse wrap handler
plugins := append(Plugins(), plugin.Plugins()...)
for i := len(plugins); i > 0; i-- {
h = plugins[i-1].Handler()(h)
}
// create the server
api := server.NewServer(Address)
api.Init(opts...)
api.Handle("/", h)
// Start API
if err := api.Start(); err != nil {
log.Fatal(err)
}
// Run server
if err := service.Run(); err != nil {
log.Fatal(err)
}
// Stop API
if err := api.Stop(); err != nil {
log.Fatal(err)
}
}
func Commands() []cli.Command {
command := cli.Command{
Name: "api",
Usage: "Run the micro API",
Action: run,
Flags: []cli.Flag{
cli.StringFlag{
Name: "address",
Usage: "Set the api address e.g 0.0.0.0:8080",
EnvVar: "MICRO_API_ADDRESS",
},
cli.StringFlag{
Name: "handler",
Usage: "Specify the request handler to be used for mapping HTTP requests to services; {api, event, http, rpc}",
EnvVar: "MICRO_API_HANDLER",
},
cli.StringFlag{
Name: "namespace",
Usage: "Set the namespace used by the API e.g. com.example.api",
EnvVar: "MICRO_API_NAMESPACE",
},
cli.StringFlag{
Name: "resolver",
Usage: "Set the hostname resolver used by the API {host, path, grpc}",
EnvVar: "MICRO_API_RESOLVER",
},
cli.StringFlag{
Name: "cors",
Usage: "Comma separated whitelist of allowed origins for CORS",
EnvVar: "MICRO_API_CORS",
},
},
}
for _, p := range Plugins() {
if cmds := p.Commands(); len(cmds) > 0 {
command.Subcommands = append(command.Subcommands, cmds...)
}
if flags := p.Flags(); len(flags) > 0 {
command.Flags = append(command.Flags, flags...)
}
}
return []cli.Command{command}
}