forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
70 lines (59 loc) · 1.39 KB
/
main.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
package main
import (
"flag"
"net/http"
"github.com/yilefreedom/go-zero/core/logx"
"github.com/yilefreedom/go-zero/core/service"
"github.com/yilefreedom/go-zero/rest"
"github.com/yilefreedom/go-zero/rest/httpx"
)
var (
port = flag.Int("port", 3333, "the port to listen")
timeout = flag.Int64("timeout", 0, "timeout of milliseconds")
)
type Request struct {
User string `form:"user,options=a|b"`
}
func first(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Middleware", "first")
next(w, r)
}
}
func second(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Middleware", "second")
next(w, r)
}
}
func handle(w http.ResponseWriter, r *http.Request) {
var req Request
err := httpx.Parse(r, &req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
httpx.OkJson(w, "helllo, "+req.User)
}
func main() {
flag.Parse()
engine := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{
Log: logx.LogConf{
Mode: "console",
},
},
Port: *port,
Timeout: *timeout,
MaxConns: 500,
}, rest.WithNotAllowedHandler(rest.CorsHandler()))
defer engine.Stop()
engine.Use(first)
engine.Use(second)
engine.AddRoute(rest.Route{
Method: http.MethodGet,
Path: "/",
Handler: handle,
})
engine.Start()
}