context.go 1.4 KB

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