This repository has been archived by the owner on Jul 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
59 lines (54 loc) · 1.41 KB
/
router.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
package idleaf
import (
"context"
"encoding/json"
"github.com/gorilla/mux"
"net/http"
"time"
)
type resp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Id int64 `json:"id"`
}
func jsonResp(resp *resp, w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
payload, err := json.Marshal(resp)
if err != nil {
payload = []byte(`{"code":1,"msg":"json marshal error","id":0}`)
}
_, _ = w.Write(payload)
}
func genDomainId(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
domain, ok := vars["domain"]
rsp := &resp{Code: errInternal}
if !ok || domain == "" {
rsp.Code = errDomainLost
rsp.Msg = "domain lost"
} else {
if id, err := idLeaf.genId(domain); err == nil {
rsp.Code = errOK
rsp.Id = id
} else {
rsp.Code = errInternal
rsp.Msg = err.Error()
}
}
jsonResp(rsp, w)
}
// InitRouter init the router with options
func InitRouter(option *Option) *mux.Router {
buffedCount = option.BuffedCount
withTimeout := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(option.TimeoutSecond)*time.Second)
defer cancel()
h.ServeHTTP(w, r.WithContext(ctx))
})
}
router := mux.NewRouter().StrictSlash(true)
router.Handle("/v1/gen/{domain}", withTimeout(http.HandlerFunc(genDomainId)))
return router
}