-
Notifications
You must be signed in to change notification settings - Fork 15
/
gin.go
73 lines (68 loc) · 1.93 KB
/
gin.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
package gin
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/shiningrush/droplet"
"github.com/shiningrush/droplet/data"
"github.com/shiningrush/droplet/log"
"github.com/shiningrush/droplet/middleware"
"github.com/shiningrush/droplet/wrapper"
"net/http"
)
func Wraps(handler droplet.Handler, opts ...wrapper.SetWrapOpt) func(*gin.Context) {
return func(ctx *gin.Context) {
opt := &wrapper.WrapOptBase{}
for i := range opts {
opts[i](opt)
}
dCtx := droplet.NewContext()
dCtx.SetContext(ctx.Request.Context())
ret, _ := droplet.NewPipe().
Add(middleware.NewRespReshapeMiddleware()).
Add(middleware.NewHttpInputMiddleWare(middleware.HttpInputOption{
ReqFunc: func() *http.Request {
return ctx.Request
},
PathParamsFunc: func(key string) string {
return ctx.Param(key)
},
InputType: opt.InputType,
IsReadFromBody: opt.IsReadFromBody,
})).
Add(middleware.NewTrafficLogMiddleware(opt.TrafficLogOpt)).
SetOrchestrator(opt.Orchestrator).
Run(handler, droplet.InitContext(dCtx))
switch ret.(type) {
case *data.FileResponse:
fr := ret.(*data.FileResponse)
if fr.ContentType == "" {
fr.ContentType = "application/octet-stream"
}
ctx.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fr.Name))
ctx.Writer.Header().Set("Content-type", fr.ContentType)
_, err := ctx.Writer.Write(fr.Content)
if err != nil {
log.Error("write response failed",
"err", err)
}
case droplet.SpecCodeHttpResponse:
resp := ret.(droplet.SpecCodeHttpResponse)
bs, err := json.Marshal(resp)
if err != nil {
log.Error("marshal result failed",
"err", err)
return
}
ctx.Data(resp.GetStatusCode(), "application/json", bs)
default:
bs, err := json.Marshal(ret)
if err != nil {
log.Error("marshal result failed",
"err", err)
return
}
ctx.Data(http.StatusOK, "application/json", bs)
}
}
}