-
Notifications
You must be signed in to change notification settings - Fork 98
/
handler.go
124 lines (108 loc) · 2.56 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package gotest
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/zhufuyi/sponge/pkg/utils"
)
// Handler info
type Handler struct {
TestData interface{}
MockDao *Dao
IHandler interface{}
Engine *gin.Engine
HTTPServer *http.Server
httpAddr string
requestAddr string
routers map[string]RouterInfo
}
// RouterInfo router info
type RouterInfo struct {
FuncName string
Method string
Path string
HandlerFunc gin.HandlerFunc
}
// NewHandler instantiated handler
func NewHandler(dao *Dao, testData interface{}) *Handler {
serverAddr, requestAddr := utils.GetLocalHTTPAddrPairs()
return &Handler{
TestData: testData,
MockDao: dao,
requestAddr: requestAddr,
httpAddr: serverAddr,
routers: make(map[string]RouterInfo),
}
}
// GoRunHTTPServer run http server
func (h *Handler) GoRunHTTPServer(fns []RouterInfo) {
if len(fns) == 0 {
panic("HandlerFunc is empty")
}
gin.SetMode(gin.ReleaseMode)
r := gin.New()
for _, fn := range fns {
switch fn.Method {
case http.MethodPost:
r.POST(fn.Path, fn.HandlerFunc)
case http.MethodDelete:
r.DELETE(fn.Path, fn.HandlerFunc)
case http.MethodPut:
r.PUT(fn.Path, fn.HandlerFunc)
case http.MethodPatch:
r.PATCH(fn.Path, fn.HandlerFunc)
case http.MethodGet:
r.GET(fn.Path, fn.HandlerFunc)
default:
fmt.Println("unsupported http method " + fn.Method)
}
h.routers[strings.ToLower(fn.FuncName)] = fn
}
h.HTTPServer = &http.Server{
Addr: h.httpAddr,
Handler: r,
}
go func() {
if err := h.HTTPServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
}
// GetRequestURL get request url from name
func (h *Handler) GetRequestURL(funcName string, pathVal ...interface{}) string {
fn, ok := h.routers[strings.ToLower(funcName)]
if !ok {
return ""
}
varCount := strings.Count(fn.Path, "/:")
if varCount == 0 || varCount != len(pathVal) {
return h.requestAddr + "/" + strings.TrimLeft(fn.Path, "/")
}
ss := strings.Split(fn.Path, "/")
var subPaths []string
j := 0
for _, s := range ss {
if len(s) > 0 {
if s[0] == ':' {
subPaths = append(subPaths, fmt.Sprintf("%v", pathVal[j]))
j++
} else {
subPaths = append(subPaths, s)
}
}
}
return h.requestAddr + "/" + strings.TrimLeft(strings.Join(subPaths, "/"), "/")
}
// Close handler
func (h *Handler) Close() {
if h.MockDao != nil {
h.MockDao.Close()
}
if h.HTTPServer != nil {
ctx, _ := context.WithTimeout(context.Background(), 3*time.Second) //nolint
_ = h.HTTPServer.Shutdown(ctx)
}
}