-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (72 loc) · 2.43 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/haibeihabo/gokitserver/services"
kitlog "github.com/go-kit/kit/log"
httptransport "github.com/go-kit/kit/transport/http"
mymux "github.com/gorilla/mux"
"golang.org/x/time/rate"
"github.com/haibeihabo/gokitserver/util"
)
func main() {
name := flag.String("name", "", "服务名称")
port := flag.Int("p", 0, "服务端口")
flag.Parse()
if *name == "" {
log.Fatal("请指定服务名称")
}
if *port == 0 {
log.Fatal("请指定服务端口号")
}
util.SetServiceNameAndPort(*name, *port)
var logger kitlog.Logger
logger = kitlog.NewLogfmtLogger(os.Stdout)
logger = kitlog.WithPrefix(logger, "mykit", "1.0")
logger = kitlog.With(logger, "time", kitlog.DefaultTimestampUTC)
logger = kitlog.With(logger, "caller", kitlog.DefaultCaller)
user := services.UserService{} // 用户服务
limiter := rate.NewLimiter(1, 5)
endp := services.RateLimit(limiter)(services.UserServiceLogMiddleware(logger)(services.CheckTokenMiddleware()(services.GetUserEndpoint(&user))))
options := []httptransport.ServerOption{
httptransport.ServerErrorEncoder(services.MyErrorEncoder),
}
serverHandler := httptransport.NewServer(endp, services.DecodeUserRequest, services.EncodeUserResponse, options...)
// 增加 handle 用于获取用户token
accessService := services.AccessService{}
accessServiceEndpoint := services.AccessEndpoint(&accessService)
accessHandler := httptransport.NewServer(accessServiceEndpoint, services.DecodeAccessRequest, services.EncodeAccessResponse, options...)
r := mymux.NewRouter()
// r.Handle(`/user/{uid:\d+}`, serverHandler)
{
r.Methods("POST").Path("/access-token").Handler(accessHandler) //注册token获取的handler
r.Methods("GET", "DELETE").Path(`/user/{uid:\d+}`).Handler(serverHandler)
r.Methods("GET").Path("/health").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json;charset=utf-8")
w.Write([]byte(`{"status": "ok"}`))
})
}
errChan := make(chan error)
go func() {
util.RegisterService()
err := http.ListenAndServe(":"+strconv.Itoa(util.ServicePort), r)
if err != nil {
log.Println(err)
errChan <- err
}
}()
go func() {
sigC := make(chan os.Signal)
signal.Notify(sigC, syscall.SIGINT, syscall.SIGTERM)
errChan <- fmt.Errorf("%s", <-sigC)
}()
getErr := <-errChan
util.DeregisterService()
log.Println(getErr)
}