context.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package http
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "os"
  7. "path"
  8. "strings"
  9. )
  10. var (
  11. defaultBinder = &DefaultBinder{}
  12. )
  13. type Context struct {
  14. ctx context.Context
  15. req *http.Request
  16. res http.ResponseWriter
  17. params map[string]string
  18. statusCode int
  19. }
  20. func (ctx *Context) reset(req *http.Request, res http.ResponseWriter, ps map[string]string) {
  21. ctx.statusCode = http.StatusOK
  22. ctx.req, ctx.res, ctx.params = req, res, ps
  23. }
  24. func (ctx *Context) Request() *http.Request {
  25. return ctx.req
  26. }
  27. func (ctx *Context) Response() http.ResponseWriter {
  28. return ctx.res
  29. }
  30. func (ctx *Context) Context() context.Context {
  31. if ctx.Request().Context() != nil {
  32. return ctx.Request().Context()
  33. }
  34. return ctx.ctx
  35. }
  36. func (ctx *Context) Bind(v any) (err error) {
  37. return defaultBinder.Bind(v, ctx.Request())
  38. }
  39. func (ctx *Context) Query(k string) string {
  40. return ctx.Request().FormValue(k)
  41. }
  42. func (ctx *Context) Param(k string) string {
  43. var (
  44. ok bool
  45. v string
  46. )
  47. if v, ok = ctx.params[k]; ok {
  48. return v
  49. }
  50. return ctx.Request().FormValue(k)
  51. }
  52. func (ctx *Context) send(res responsePayload) (err error) {
  53. ctx.Response().Header().Set("Content-Type", "application/json")
  54. encoder := json.NewEncoder(ctx.Response())
  55. if strings.HasPrefix(ctx.Request().Header.Get("User-Agent"), "curl") {
  56. encoder.SetIndent("", "\t")
  57. }
  58. return encoder.Encode(res)
  59. }
  60. func (ctx *Context) Success(v any) (err error) {
  61. return ctx.send(responsePayload{Data: v})
  62. }
  63. func (ctx *Context) Status(code int) {
  64. ctx.statusCode = code
  65. }
  66. func (ctx *Context) Error(code int, reason string) (err error) {
  67. return ctx.send(responsePayload{Code: code, Reason: reason})
  68. }
  69. func (ctx *Context) Redirect(url string, code int) {
  70. if code != http.StatusFound && code != http.StatusMovedPermanently {
  71. code = http.StatusMovedPermanently
  72. }
  73. http.Redirect(ctx.Response(), ctx.Request(), url, code)
  74. }
  75. func (ctx *Context) SetCookie(cookie *http.Cookie) {
  76. http.SetCookie(ctx.Response(), cookie)
  77. }
  78. func (ctx *Context) SendFile(filename string) (err error) {
  79. var (
  80. fi os.FileInfo
  81. fp *os.File
  82. )
  83. if fi, err = os.Stat(filename); err == nil {
  84. if fp, err = os.Open(filename); err == nil {
  85. http.ServeContent(ctx.Response(), ctx.Request(), path.Base(filename), fi.ModTime(), fp)
  86. err = fp.Close()
  87. }
  88. }
  89. return
  90. }