context.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. _UserID = "_user_id_"
  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. // UserID 获取 UserID
  89. UserID() uint64
  90. SetUserID(userID uint64)
  91. // Authorization 获取请求认证信息
  92. Authorization() string
  93. // Alias 设置路由别名 for metrics uri
  94. Alias() string
  95. setAlias(path string)
  96. // RequestInputParams 获取所有参数
  97. RequestInputParams() url.Values
  98. // RequestQueryParams 获取 Query 参数
  99. RequestQueryParams() url.Values
  100. // RequestPostFormParams 获取 PostForm 参数
  101. RequestPostFormParams() url.Values
  102. // Request 获取 Request 对象
  103. Request() *http.Request
  104. // RawData 获取 Request.Body
  105. RawData() []byte
  106. // Method 获取 Request.Method
  107. Method() string
  108. // Host 获取 Request.Host
  109. Host() string
  110. // Path 获取 请求的路径 Request.URL.Path (不附带 querystring)
  111. Path() string
  112. // URI 获取 unescape 后的 Request.URL.RequestURI()
  113. URI() string
  114. // RequestContext 获取请求的 context (当 client 关闭后,会自动 canceled)
  115. RequestContext() StdContext
  116. // ResponseWriter 获取 ResponseWriter 对象
  117. ResponseWriter() gin.ResponseWriter
  118. }
  119. type context struct {
  120. ctx *gin.Context
  121. }
  122. type StdContext struct {
  123. stdCtx.Context
  124. Trace
  125. *zap.Logger
  126. }
  127. func (c *context) init() {
  128. body, err := c.ctx.GetRawData()
  129. if err != nil {
  130. panic(err)
  131. }
  132. c.ctx.Set(_BodyName, body) // cache body是为了trace使用
  133. c.ctx.Request.Body = io.NopCloser(bytes.NewBuffer(body)) // re-construct req body
  134. }
  135. func (c *context) Context() *gin.Context {
  136. return c.ctx
  137. }
  138. // ShouldBindQuery 反序列化querystring
  139. // tag: `form:"xxx"` (注:不要写成query)
  140. func (c *context) ShouldBindQuery(obj any) error {
  141. return c.ctx.ShouldBindWith(obj, binding.Query)
  142. }
  143. // ShouldBindPostForm 反序列化 postform (querystring 会被忽略)
  144. // tag: `form:"xxx"`
  145. func (c *context) ShouldBindPostForm(obj any) error {
  146. return c.ctx.ShouldBindWith(obj, binding.FormPost)
  147. }
  148. // ShouldBindForm 同时反序列化querystring和postform;
  149. // 当querystring和postform存在相同字段时,postform优先使用。
  150. // tag: `form:"xxx"`
  151. func (c *context) ShouldBindForm(obj any) error {
  152. return c.ctx.ShouldBindWith(obj, binding.Form)
  153. }
  154. // ShouldBindJSON 反序列化postjson
  155. // tag: `json:"xxx"`
  156. func (c *context) ShouldBindJSON(obj any) error {
  157. return c.ctx.ShouldBindWith(obj, binding.JSON)
  158. }
  159. // ShouldBindURI 反序列化path参数(如路由路径为 /user/:name)
  160. // tag: `uri:"xxx"`
  161. func (c *context) ShouldBindURI(obj any) error {
  162. return c.ctx.ShouldBindUri(obj)
  163. }
  164. // Redirect 重定向
  165. func (c *context) Redirect(code int, location string) {
  166. c.ctx.Redirect(code, location)
  167. }
  168. func (c *context) Trace() Trace {
  169. t, ok := c.ctx.Get(_TraceName)
  170. if !ok || t == nil {
  171. return nil
  172. }
  173. return t.(Trace)
  174. }
  175. func (c *context) setTrace(trace Trace) {
  176. c.ctx.Set(_TraceName, trace)
  177. }
  178. func (c *context) disableTrace() {
  179. c.setTrace(nil)
  180. }
  181. func (c *context) Logger() *zap.Logger {
  182. logger, ok := c.ctx.Get(_LoggerName)
  183. if !ok {
  184. return nil
  185. }
  186. return logger.(*zap.Logger)
  187. }
  188. func (c *context) setLogger(logger *zap.Logger) {
  189. c.ctx.Set(_LoggerName, logger)
  190. }
  191. func (c *context) getPayload() any {
  192. if payload, ok := c.ctx.Get(_PayloadName); ok != false {
  193. return payload
  194. }
  195. return nil
  196. }
  197. func (c *context) Payload(payload any) {
  198. c.ctx.Set(_PayloadName, payload)
  199. }
  200. func (c *context) getGraphPayload() any {
  201. if payload, ok := c.ctx.Get(_GraphPayloadName); ok != false {
  202. return payload
  203. }
  204. return nil
  205. }
  206. func (c *context) GraphPayload(payload any) {
  207. c.ctx.Set(_GraphPayloadName, payload)
  208. }
  209. func (c *context) HTML(name string, obj any) {
  210. c.ctx.HTML(200, name+".html", obj)
  211. }
  212. func (c *context) Header() http.Header {
  213. header := c.ctx.Request.Header
  214. clone := make(http.Header, len(header))
  215. for k, v := range header {
  216. value := make([]string, len(v))
  217. copy(value, v)
  218. clone[k] = value
  219. }
  220. return clone
  221. }
  222. func (c *context) GetHeader(key string) string {
  223. return c.ctx.GetHeader(key)
  224. }
  225. func (c *context) SetHeader(key, value string) {
  226. c.ctx.Header(key, value)
  227. }
  228. func (c *context) UserID() uint64 {
  229. val, ok := c.ctx.Get(_UserID)
  230. if !ok {
  231. return 0
  232. }
  233. return val.(uint64)
  234. }
  235. func (c *context) SetUserID(userID uint64) {
  236. c.ctx.Set(_UserID, userID)
  237. }
  238. func (c *context) Authorization() string {
  239. return c.ctx.GetHeader("Authorization")
  240. }
  241. func (c *context) AbortWithError(err errno.Error) {
  242. if err != nil {
  243. httpCode := err.GetHttpCode()
  244. if httpCode == 0 {
  245. httpCode = http.StatusInternalServerError
  246. }
  247. c.ctx.AbortWithStatus(httpCode)
  248. c.ctx.Set(_AbortErrorName, err)
  249. }
  250. }
  251. func (c *context) abortError() errno.Error {
  252. err, _ := c.ctx.Get(_AbortErrorName)
  253. return err.(errno.Error)
  254. }
  255. func (c *context) Alias() string {
  256. path, ok := c.ctx.Get(_Alias)
  257. if !ok {
  258. return ""
  259. }
  260. return path.(string)
  261. }
  262. func (c *context) setAlias(path string) {
  263. if path = strings.TrimSpace(path); path != "" {
  264. c.ctx.Set(_Alias, path)
  265. }
  266. }
  267. // RequestInputParams 获取所有参数
  268. func (c *context) RequestInputParams() url.Values {
  269. _ = c.ctx.Request.ParseForm()
  270. return c.ctx.Request.Form
  271. }
  272. // RequestQueryParams 获取Query参数
  273. func (c *context) RequestQueryParams() url.Values {
  274. query, _ := url.ParseQuery(c.ctx.Request.URL.RawQuery)
  275. return query
  276. }
  277. // RequestPostFormParams 获取 PostForm 参数
  278. func (c *context) RequestPostFormParams() url.Values {
  279. _ = c.ctx.Request.ParseForm()
  280. return c.ctx.Request.PostForm
  281. }
  282. // Request 获取 Request
  283. func (c *context) Request() *http.Request {
  284. return c.ctx.Request
  285. }
  286. func (c *context) RawData() []byte {
  287. body, ok := c.ctx.Get(_BodyName)
  288. if !ok {
  289. return nil
  290. }
  291. return body.([]byte)
  292. }
  293. // Method 请求的method
  294. func (c *context) Method() string {
  295. return c.ctx.Request.Method
  296. }
  297. // Host 请求的host
  298. func (c *context) Host() string {
  299. return c.ctx.Request.Host
  300. }
  301. // Path 请求的路径(不附带querystring)
  302. func (c *context) Path() string {
  303. return c.ctx.Request.URL.Path
  304. }
  305. // URI unescape后的uri
  306. func (c *context) URI() string {
  307. uri, _ := url.QueryUnescape(c.ctx.Request.URL.RequestURI())
  308. return uri
  309. }
  310. // RequestContext (包装 Trace + Logger) 获取请求的 context (当client关闭后,会自动canceled)
  311. func (c *context) RequestContext() StdContext {
  312. return StdContext{
  313. //c.ctx.Request.Context(),
  314. stdCtx.Background(),
  315. c.Trace(),
  316. c.Logger(),
  317. }
  318. }
  319. // ResponseWriter 获取 ResponseWriter
  320. func (c *context) ResponseWriter() gin.ResponseWriter {
  321. return c.ctx.Writer
  322. }