context.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package http
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strings"
  6. )
  7. var (
  8. binder = &DefaultBinder{}
  9. )
  10. type Context struct {
  11. request *http.Request
  12. response http.ResponseWriter
  13. params map[string]string
  14. }
  15. func (c *Context) Reset(r *http.Request, w http.ResponseWriter, params map[string]string) {
  16. c.request = r
  17. c.response = w
  18. c.params = params
  19. }
  20. func (c *Context) Request() *http.Request {
  21. return c.request
  22. }
  23. func (c *Context) Response() http.ResponseWriter {
  24. return c.response
  25. }
  26. func (c *Context) FormValue(name string) string {
  27. return c.request.FormValue(name)
  28. }
  29. func (c *Context) Bind(i interface{}) (err error) {
  30. return binder.Bind(i, c.Request())
  31. }
  32. func (c *Context) Success(val interface{}) (err error) {
  33. c.response.Header().Set("Content-Type", "application/json")
  34. enc := json.NewEncoder(c.response)
  35. if strings.Contains(c.request.Header.Get("User-Agent"), "curl") {
  36. enc.SetIndent("", "\t")
  37. }
  38. if err = enc.Encode(&Response{Result: val}); err != nil {
  39. c.response.WriteHeader(http.StatusBadGateway)
  40. }
  41. return
  42. }
  43. func (c *Context) Error(code int, message string) (err error) {
  44. c.response.Header().Set("Content-Type", "application/json")
  45. enc := json.NewEncoder(c.response)
  46. if strings.Contains(c.request.Header.Get("User-Agent"), "curl") {
  47. enc.SetIndent("", "\t")
  48. }
  49. if err = enc.Encode(&Response{Code: code, Message: message}); err != nil {
  50. c.response.WriteHeader(http.StatusBadGateway)
  51. }
  52. return
  53. }
  54. func (c *Context) SetParam(name string, value string) {
  55. if c.params == nil {
  56. c.params = make(map[string]string)
  57. }
  58. c.params[name] = value
  59. }
  60. func (c *Context) ParamValue(name string) string {
  61. if c.params != nil {
  62. return c.params[name]
  63. }
  64. return ""
  65. }