context.go 1.8 KB

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