context.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. package core
  2. import (
  3. "bytes"
  4. stdctx "context"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "sync"
  10. "github.com/xinliangnote/go-gin-api/internal/proposal"
  11. "github.com/xinliangnote/go-gin-api/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. _SessionUserInfo = "_session_user_info"
  26. _AbortErrorName = "_abort_error_"
  27. _IsRecordMetrics = "_is_record_metrics_"
  28. )
  29. var contextPool = &sync.Pool{
  30. New: func() interface{} {
  31. return new(context)
  32. },
  33. }
  34. func newContext(ctx *gin.Context) Context {
  35. context := contextPool.Get().(*context)
  36. context.ctx = ctx
  37. return context
  38. }
  39. func releaseContext(ctx Context) {
  40. c := ctx.(*context)
  41. c.ctx = nil
  42. contextPool.Put(c)
  43. }
  44. var _ Context = (*context)(nil)
  45. type Context interface {
  46. init()
  47. // ShouldBindQuery 反序列化 querystring
  48. // tag: `form:"xxx"` (注:不要写成 query)
  49. ShouldBindQuery(obj interface{}) error
  50. // ShouldBindPostForm 反序列化 postform (querystring会被忽略)
  51. // tag: `form:"xxx"`
  52. ShouldBindPostForm(obj interface{}) error
  53. // ShouldBindForm 同时反序列化 querystring 和 postform;
  54. // 当 querystring 和 postform 存在相同字段时,postform 优先使用。
  55. // tag: `form:"xxx"`
  56. ShouldBindForm(obj interface{}) error
  57. // ShouldBindJSON 反序列化 postjson
  58. // tag: `json:"xxx"`
  59. ShouldBindJSON(obj interface{}) error
  60. // ShouldBindURI 反序列化 path 参数(如路由路径为 /user/:name)
  61. // tag: `uri:"xxx"`
  62. ShouldBindURI(obj interface{}) error
  63. // Redirect 重定向
  64. Redirect(code int, location string)
  65. // Trace 获取 Trace 对象
  66. Trace() Trace
  67. setTrace(trace Trace)
  68. disableTrace()
  69. // Logger 获取 Logger 对象
  70. Logger() *zap.Logger
  71. setLogger(logger *zap.Logger)
  72. // Payload 正确返回
  73. Payload(payload interface{})
  74. getPayload() interface{}
  75. // GraphPayload GraphQL返回值 与 api 返回结构不同
  76. GraphPayload(payload interface{})
  77. getGraphPayload() interface{}
  78. // HTML 返回界面
  79. HTML(name string, obj interface{})
  80. // AbortWithError 错误返回
  81. AbortWithError(err BusinessError)
  82. abortError() BusinessError
  83. // Header 获取 Header 对象
  84. Header() http.Header
  85. // GetHeader 获取 Header
  86. GetHeader(key string) string
  87. // SetHeader 设置 Header
  88. SetHeader(key, value string)
  89. // SessionUserInfo 当前用户信息
  90. SessionUserInfo() proposal.SessionUserInfo
  91. setSessionUserInfo(info proposal.SessionUserInfo)
  92. // Alias 设置路由别名 for metrics path
  93. Alias() string
  94. setAlias(path string)
  95. // disableRecordMetrics 设置禁止记录指标
  96. disableRecordMetrics()
  97. ableRecordMetrics()
  98. isRecordMetrics() bool
  99. // RequestInputParams 获取所有参数
  100. RequestInputParams() 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 = ioutil.NopCloser(bytes.NewBuffer(body)) // re-construct req body
  135. }
  136. // ShouldBindQuery 反序列化querystring
  137. // tag: `form:"xxx"` (注:不要写成query)
  138. func (c *context) ShouldBindQuery(obj interface{}) error {
  139. return c.ctx.ShouldBindWith(obj, binding.Query)
  140. }
  141. // ShouldBindPostForm 反序列化 postform (querystring 会被忽略)
  142. // tag: `form:"xxx"`
  143. func (c *context) ShouldBindPostForm(obj interface{}) error {
  144. return c.ctx.ShouldBindWith(obj, binding.FormPost)
  145. }
  146. // ShouldBindForm 同时反序列化querystring和postform;
  147. // 当querystring和postform存在相同字段时,postform优先使用。
  148. // tag: `form:"xxx"`
  149. func (c *context) ShouldBindForm(obj interface{}) error {
  150. return c.ctx.ShouldBindWith(obj, binding.Form)
  151. }
  152. // ShouldBindJSON 反序列化postjson
  153. // tag: `json:"xxx"`
  154. func (c *context) ShouldBindJSON(obj interface{}) error {
  155. return c.ctx.ShouldBindWith(obj, binding.JSON)
  156. }
  157. // ShouldBindURI 反序列化path参数(如路由路径为 /user/:name)
  158. // tag: `uri:"xxx"`
  159. func (c *context) ShouldBindURI(obj interface{}) error {
  160. return c.ctx.ShouldBindUri(obj)
  161. }
  162. // Redirect 重定向
  163. func (c *context) Redirect(code int, location string) {
  164. c.ctx.Redirect(code, location)
  165. }
  166. func (c *context) Trace() Trace {
  167. t, ok := c.ctx.Get(_TraceName)
  168. if !ok || t == nil {
  169. return nil
  170. }
  171. return t.(Trace)
  172. }
  173. func (c *context) setTrace(trace Trace) {
  174. c.ctx.Set(_TraceName, trace)
  175. }
  176. func (c *context) disableTrace() {
  177. c.setTrace(nil)
  178. }
  179. func (c *context) Logger() *zap.Logger {
  180. logger, ok := c.ctx.Get(_LoggerName)
  181. if !ok {
  182. return nil
  183. }
  184. return logger.(*zap.Logger)
  185. }
  186. func (c *context) setLogger(logger *zap.Logger) {
  187. c.ctx.Set(_LoggerName, logger)
  188. }
  189. func (c *context) getPayload() interface{} {
  190. if payload, ok := c.ctx.Get(_PayloadName); ok != false {
  191. return payload
  192. }
  193. return nil
  194. }
  195. func (c *context) Payload(payload interface{}) {
  196. c.ctx.Set(_PayloadName, payload)
  197. }
  198. func (c *context) getGraphPayload() interface{} {
  199. if payload, ok := c.ctx.Get(_GraphPayloadName); ok != false {
  200. return payload
  201. }
  202. return nil
  203. }
  204. func (c *context) GraphPayload(payload interface{}) {
  205. c.ctx.Set(_GraphPayloadName, payload)
  206. }
  207. func (c *context) HTML(name string, obj interface{}) {
  208. c.ctx.HTML(200, name+".html", obj)
  209. }
  210. func (c *context) Header() http.Header {
  211. header := c.ctx.Request.Header
  212. clone := make(http.Header, len(header))
  213. for k, v := range header {
  214. value := make([]string, len(v))
  215. copy(value, v)
  216. clone[k] = value
  217. }
  218. return clone
  219. }
  220. func (c *context) GetHeader(key string) string {
  221. return c.ctx.GetHeader(key)
  222. }
  223. func (c *context) SetHeader(key, value string) {
  224. c.ctx.Header(key, value)
  225. }
  226. func (c *context) SessionUserInfo() proposal.SessionUserInfo {
  227. val, ok := c.ctx.Get(_SessionUserInfo)
  228. if !ok {
  229. return proposal.SessionUserInfo{}
  230. }
  231. return val.(proposal.SessionUserInfo)
  232. }
  233. func (c *context) setSessionUserInfo(info proposal.SessionUserInfo) {
  234. c.ctx.Set(_SessionUserInfo, info)
  235. }
  236. func (c *context) AbortWithError(err BusinessError) {
  237. if err != nil {
  238. httpCode := err.HTTPCode()
  239. if httpCode == 0 {
  240. httpCode = http.StatusInternalServerError
  241. }
  242. c.ctx.AbortWithStatus(httpCode)
  243. c.ctx.Set(_AbortErrorName, err)
  244. }
  245. }
  246. func (c *context) abortError() BusinessError {
  247. err, _ := c.ctx.Get(_AbortErrorName)
  248. return err.(BusinessError)
  249. }
  250. func (c *context) Alias() string {
  251. path, ok := c.ctx.Get(_Alias)
  252. if !ok {
  253. return ""
  254. }
  255. return path.(string)
  256. }
  257. func (c *context) setAlias(path string) {
  258. if path = strings.TrimSpace(path); path != "" {
  259. c.ctx.Set(_Alias, path)
  260. }
  261. }
  262. func (c *context) isRecordMetrics() bool {
  263. isRecordMetrics, ok := c.ctx.Get(_IsRecordMetrics)
  264. if !ok {
  265. return false
  266. }
  267. return isRecordMetrics.(bool)
  268. }
  269. func (c *context) ableRecordMetrics() {
  270. c.ctx.Set(_IsRecordMetrics, true)
  271. }
  272. func (c *context) disableRecordMetrics() {
  273. c.ctx.Set(_IsRecordMetrics, false)
  274. }
  275. // RequestInputParams 获取所有参数
  276. func (c *context) RequestInputParams() url.Values {
  277. _ = c.ctx.Request.ParseForm()
  278. return c.ctx.Request.Form
  279. }
  280. // RequestPostFormParams 获取 PostForm 参数
  281. func (c *context) RequestPostFormParams() url.Values {
  282. _ = c.ctx.Request.ParseForm()
  283. return c.ctx.Request.PostForm
  284. }
  285. // Request 获取 Request
  286. func (c *context) Request() *http.Request {
  287. return c.ctx.Request
  288. }
  289. func (c *context) RawData() []byte {
  290. body, ok := c.ctx.Get(_BodyName)
  291. if !ok {
  292. return nil
  293. }
  294. return body.([]byte)
  295. }
  296. // Method 请求的method
  297. func (c *context) Method() string {
  298. return c.ctx.Request.Method
  299. }
  300. // Host 请求的host
  301. func (c *context) Host() string {
  302. return c.ctx.Request.Host
  303. }
  304. // Path 请求的路径(不附带querystring)
  305. func (c *context) Path() string {
  306. return c.ctx.Request.URL.Path
  307. }
  308. // URI unescape后的uri
  309. func (c *context) URI() string {
  310. uri, _ := url.QueryUnescape(c.ctx.Request.URL.RequestURI())
  311. return uri
  312. }
  313. // RequestContext (包装 Trace + Logger) 获取请求的 context (当client关闭后,会自动canceled)
  314. func (c *context) RequestContext() StdContext {
  315. return StdContext{
  316. //c.ctx.Request.Context(),
  317. stdctx.Background(),
  318. c.Trace(),
  319. c.Logger(),
  320. }
  321. }
  322. // ResponseWriter 获取 ResponseWriter
  323. func (c *context) ResponseWriter() gin.ResponseWriter {
  324. return c.ctx.Writer
  325. }