context.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package mux
  2. import (
  3. "bytes"
  4. stdCtx "context"
  5. "io"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "sync"
  10. "git.bvbej.com/bvbej/base-golang/pkg/errno"
  11. "git.bvbej.com/bvbej/base-golang/pkg/trace"
  12. "github.com/gin-gonic/gin"
  13. "github.com/gin-gonic/gin/binding"
  14. "go.uber.org/zap"
  15. )
  16. type HandlerFunc func(c Context)
  17. type Trace = trace.T
  18. const (
  19. _Alias = "_alias_"
  20. _TraceName = "_trace_"
  21. _LoggerName = "_logger_"
  22. _BodyName = "_body_"
  23. _PayloadName = "_payload_"
  24. _GraphPayloadName = "_graph_payload_"
  25. _AbortErrorName = "_abort_error_"
  26. _Auth = "_auth_"
  27. )
  28. var contextPool = &sync.Pool{
  29. New: func() any {
  30. return new(context)
  31. },
  32. }
  33. func newContext(ctx *gin.Context) Context {
  34. getContext := contextPool.Get().(*context)
  35. getContext.ctx = ctx
  36. return getContext
  37. }
  38. func releaseContext(ctx Context) {
  39. c := ctx.(*context)
  40. c.ctx = nil
  41. contextPool.Put(c)
  42. }
  43. var _ Context = (*context)(nil)
  44. type Context interface {
  45. init()
  46. Context() *gin.Context
  47. // ShouldBindQuery 反序列化 query
  48. // tag: `form:"xxx"` (注:不要写成 query)
  49. ShouldBindQuery(obj any) error
  50. // ShouldBindPostForm 反序列化 x-www-from-urlencoded
  51. // tag: `form:"xxx"`
  52. ShouldBindPostForm(obj any) error
  53. // ShouldBindForm 同时反序列化 form-data;
  54. // tag: `form:"xxx"`
  55. ShouldBindForm(obj any) error
  56. // ShouldBindJSON 反序列化 post-json
  57. // tag: `json:"xxx"`
  58. ShouldBindJSON(obj any) error
  59. // ShouldBindURI 反序列化 path 参数(如路由路径为 /user/:name)
  60. // tag: `uri:"xxx"`
  61. ShouldBindURI(obj any) error
  62. // Redirect 重定向
  63. Redirect(code int, location string)
  64. // Trace 获取 Trace 对象
  65. Trace() Trace
  66. setTrace(trace Trace)
  67. disableTrace()
  68. // Logger 获取 Logger 对象
  69. Logger() *zap.Logger
  70. setLogger(logger *zap.Logger)
  71. // Payload 正确返回
  72. Payload(payload any)
  73. getPayload() any
  74. // GraphPayload GraphQL返回值 与 api 返回结构不同
  75. GraphPayload(payload any)
  76. getGraphPayload() any
  77. // HTML 返回界面
  78. HTML(name string, obj any)
  79. // AbortWithError 错误返回
  80. AbortWithError(err errno.Error)
  81. abortError() errno.Error
  82. // Header 获取 Header 对象
  83. Header() http.Header
  84. // GetHeader 获取 Header
  85. GetHeader(key string) string
  86. // SetHeader 设置 Header
  87. SetHeader(key, value string)
  88. Auth() any
  89. SetAuth(auth any)
  90. // Authorization 获取请求认证信息
  91. Authorization() string
  92. // Platform 平台标识
  93. Platform() string
  94. // Alias 设置路由别名 for metrics uri
  95. Alias() string
  96. setAlias(path string)
  97. // RequestInputParams 获取所有参数
  98. RequestInputParams() url.Values
  99. // RequestQueryParams 获取 Query 参数
  100. RequestQueryParams() url.Values
  101. // RequestPostFormParams 获取 PostForm 参数
  102. RequestPostFormParams() url.Values
  103. // Request 获取 Request 对象
  104. Request() *http.Request
  105. // RawData 获取 Request.Body
  106. RawData() []byte
  107. // Method 获取 Request.Method
  108. Method() string
  109. // Host 获取 Request.Host
  110. Host() string
  111. // Path 获取 请求的路径 Request.URL.Path (不附带 querystring)
  112. Path() string
  113. // URI 获取 unescape 后的 Request.URL.RequestURI()
  114. URI() string
  115. // RequestContext 获取请求的 context (当 client 关闭后,会自动 canceled)
  116. RequestContext() StdContext
  117. // ResponseWriter 获取 ResponseWriter 对象
  118. ResponseWriter() gin.ResponseWriter
  119. }
  120. type context struct {
  121. ctx *gin.Context
  122. }
  123. type StdContext struct {
  124. stdCtx.Context
  125. Trace
  126. *zap.Logger
  127. }
  128. func (c *context) init() {
  129. body, err := c.ctx.GetRawData()
  130. if err != nil {
  131. panic(err)
  132. }
  133. c.ctx.Set(_BodyName, body) // cache body是为了trace使用
  134. c.ctx.Request.Body = io.NopCloser(bytes.NewBuffer(body)) // re-construct req body
  135. }
  136. func (c *context) Context() *gin.Context {
  137. return c.ctx
  138. }
  139. // ShouldBindQuery 反序列化querystring
  140. // tag: `form:"xxx"` (注:不要写成query)
  141. func (c *context) ShouldBindQuery(obj any) error {
  142. return c.ctx.ShouldBindWith(obj, binding.Query)
  143. }
  144. // ShouldBindPostForm 反序列化 postform (querystring 会被忽略)
  145. // tag: `form:"xxx"`
  146. func (c *context) ShouldBindPostForm(obj any) error {
  147. return c.ctx.ShouldBindWith(obj, binding.FormPost)
  148. }
  149. // ShouldBindForm 同时反序列化querystring和postform;
  150. // 当querystring和postform存在相同字段时,postform优先使用。
  151. // tag: `form:"xxx"`
  152. func (c *context) ShouldBindForm(obj any) error {
  153. return c.ctx.ShouldBindWith(obj, binding.Form)
  154. }
  155. // ShouldBindJSON 反序列化postjson
  156. // tag: `json:"xxx"`
  157. func (c *context) ShouldBindJSON(obj any) error {
  158. return c.ctx.ShouldBindWith(obj, binding.JSON)
  159. }
  160. // ShouldBindURI 反序列化path参数(如路由路径为 /user/:name)
  161. // tag: `uri:"xxx"`
  162. func (c *context) ShouldBindURI(obj any) error {
  163. return c.ctx.ShouldBindUri(obj)
  164. }
  165. // Redirect 重定向
  166. func (c *context) Redirect(code int, location string) {
  167. c.ctx.Redirect(code, location)
  168. }
  169. func (c *context) Trace() Trace {
  170. t, ok := c.ctx.Get(_TraceName)
  171. if !ok || t == nil {
  172. return nil
  173. }
  174. return t.(Trace)
  175. }
  176. func (c *context) setTrace(trace Trace) {
  177. c.ctx.Set(_TraceName, trace)
  178. }
  179. func (c *context) disableTrace() {
  180. c.setTrace(nil)
  181. }
  182. func (c *context) Logger() *zap.Logger {
  183. logger, ok := c.ctx.Get(_LoggerName)
  184. if !ok {
  185. return nil
  186. }
  187. return logger.(*zap.Logger)
  188. }
  189. func (c *context) setLogger(logger *zap.Logger) {
  190. c.ctx.Set(_LoggerName, logger)
  191. }
  192. func (c *context) getPayload() any {
  193. if payload, ok := c.ctx.Get(_PayloadName); ok != false {
  194. return payload
  195. }
  196. return nil
  197. }
  198. func (c *context) Payload(payload any) {
  199. c.ctx.Set(_PayloadName, payload)
  200. }
  201. func (c *context) getGraphPayload() any {
  202. if payload, ok := c.ctx.Get(_GraphPayloadName); ok != false {
  203. return payload
  204. }
  205. return nil
  206. }
  207. func (c *context) GraphPayload(payload any) {
  208. c.ctx.Set(_GraphPayloadName, payload)
  209. }
  210. func (c *context) HTML(name string, obj any) {
  211. c.ctx.HTML(200, name+".html", obj)
  212. }
  213. func (c *context) Header() http.Header {
  214. header := c.ctx.Request.Header
  215. clone := make(http.Header, len(header))
  216. for k, v := range header {
  217. value := make([]string, len(v))
  218. copy(value, v)
  219. clone[k] = value
  220. }
  221. return clone
  222. }
  223. func (c *context) GetHeader(key string) string {
  224. return c.ctx.GetHeader(key)
  225. }
  226. func (c *context) SetHeader(key, value string) {
  227. c.ctx.Header(key, value)
  228. }
  229. func (c *context) Auth() any {
  230. val, ok := c.ctx.Get(_Auth)
  231. if !ok {
  232. return nil
  233. }
  234. return val
  235. }
  236. func (c *context) SetAuth(auth any) {
  237. c.ctx.Set(_Auth, auth)
  238. }
  239. func (c *context) Authorization() string {
  240. return c.ctx.GetHeader("Authorization")
  241. }
  242. func (c *context) Platform() string {
  243. return c.ctx.GetHeader("X-Platform")
  244. }
  245. func (c *context) AbortWithError(err errno.Error) {
  246. if err != nil {
  247. httpCode := err.GetHttpCode()
  248. if httpCode == 0 {
  249. httpCode = http.StatusInternalServerError
  250. }
  251. c.ctx.AbortWithStatus(httpCode)
  252. c.ctx.Set(_AbortErrorName, err)
  253. }
  254. }
  255. func (c *context) abortError() errno.Error {
  256. err, _ := c.ctx.Get(_AbortErrorName)
  257. return err.(errno.Error)
  258. }
  259. func (c *context) Alias() string {
  260. path, ok := c.ctx.Get(_Alias)
  261. if !ok {
  262. return ""
  263. }
  264. return path.(string)
  265. }
  266. func (c *context) setAlias(path string) {
  267. if path = strings.TrimSpace(path); path != "" {
  268. c.ctx.Set(_Alias, path)
  269. }
  270. }
  271. // RequestInputParams 获取所有参数
  272. func (c *context) RequestInputParams() url.Values {
  273. _ = c.ctx.Request.ParseForm()
  274. return c.ctx.Request.Form
  275. }
  276. // RequestQueryParams 获取Query参数
  277. func (c *context) RequestQueryParams() url.Values {
  278. query, _ := url.ParseQuery(c.ctx.Request.URL.RawQuery)
  279. return query
  280. }
  281. // RequestPostFormParams 获取 PostForm 参数
  282. func (c *context) RequestPostFormParams() url.Values {
  283. _ = c.ctx.Request.ParseForm()
  284. return c.ctx.Request.PostForm
  285. }
  286. // Request 获取 Request
  287. func (c *context) Request() *http.Request {
  288. return c.ctx.Request
  289. }
  290. func (c *context) RawData() []byte {
  291. body, ok := c.ctx.Get(_BodyName)
  292. if !ok {
  293. return nil
  294. }
  295. return body.([]byte)
  296. }
  297. // Method 请求的method
  298. func (c *context) Method() string {
  299. return c.ctx.Request.Method
  300. }
  301. // Host 请求的host
  302. func (c *context) Host() string {
  303. return c.ctx.Request.Host
  304. }
  305. // Path 请求的路径(不附带querystring)
  306. func (c *context) Path() string {
  307. return c.ctx.Request.URL.Path
  308. }
  309. // URI unescape后的uri
  310. func (c *context) URI() string {
  311. uri, _ := url.QueryUnescape(c.ctx.Request.URL.RequestURI())
  312. return uri
  313. }
  314. // RequestContext (包装 Trace + Logger) 获取请求的 context (当client关闭后,会自动canceled)
  315. func (c *context) RequestContext() StdContext {
  316. return StdContext{
  317. //c.ctx.Request.Context(),
  318. stdCtx.Background(),
  319. c.Trace(),
  320. c.Logger(),
  321. }
  322. }
  323. // ResponseWriter 获取 ResponseWriter
  324. func (c *context) ResponseWriter() gin.ResponseWriter {
  325. return c.ctx.Writer
  326. }