-
Notifications
You must be signed in to change notification settings - Fork 3
/
gin_utils.go
59 lines (50 loc) · 1.42 KB
/
gin_utils.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 webtest
import (
"context"
"github.com/cisco-open/go-lanai/pkg/web"
"github.com/gin-gonic/gin"
"io"
"net/http"
"net/http/httptest"
"sync"
)
const ginContextRecorder = `_go-lanai/webtest/gin/recorder`
type ginContextCreator struct {
sync.Once
engine *gin.Engine
}
func (c *ginContextCreator) LazyInit() {
c.Do(func() {
gin.SetMode(gin.ReleaseMode)
c.engine = gin.New()
c.engine.ContextWithFallback = true
})
}
func (c *ginContextCreator) CreateWithRequest(req *http.Request) *gin.Context {
c.LazyInit()
rw := httptest.NewRecorder()
gc := gin.CreateTestContextOnly(rw, c.engine)
gc.Set(ginContextRecorder, rw)
if req != nil {
gc.Request = req
web.GinContextMerger()(gc)
}
return gc
}
var defaultGinContextCreator = &ginContextCreator{}
func NewGinContext(ctx context.Context, method, path string, body io.Reader, opts ...RequestOptions) *gin.Context {
req := httptest.NewRequest(method, path, body).WithContext(ctx)
for _, fn := range opts {
if fn != nil {
fn(req)
}
}
return NewGinContextWithRequest(req)
}
func NewGinContextWithRequest(req *http.Request) *gin.Context {
return defaultGinContextCreator.CreateWithRequest(req)
}
func GinContextRecorder(gc *gin.Context) *httptest.ResponseRecorder {
recorder, _ := gc.Value(ginContextRecorder).(*httptest.ResponseRecorder)
return recorder
}