response.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package xhttp
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. "net/http"
  6. "net/url"
  7. "git.chuangxin1.com/myth/sacred"
  8. )
  9. // Message HTTP response
  10. type Message struct {
  11. req *http.Request
  12. res *http.Response
  13. StatusCode int
  14. Body []byte
  15. Header http.Header
  16. }
  17. // JSON Body to JSON
  18. func (m Message) JSON(v interface{}) error {
  19. return json.Unmarshal(m.Body, v)
  20. }
  21. // XML Body to XML
  22. func (m Message) XML(v interface{}) error {
  23. return xml.Unmarshal(m.Body, v)
  24. }
  25. // Cookies parses and returns the cookies set in the Set-Cookie headers.
  26. func (m Message) Cookies() []*http.Cookie {
  27. return m.res.Cookies()
  28. }
  29. // Location returns the URL of the response's "Location" header, if present. Relative redirects are resolved relative to the Response's Request. ErrNoLocation is returned if no Location header is present.
  30. func (m Message) Location() (*url.URL, error) {
  31. return m.res.Location()
  32. }
  33. // UserAgent returns the client's User-Agent, if sent in the request.
  34. func (m Message) UserAgent() string {
  35. return m.req.UserAgent()
  36. }
  37. // Referer returns the referring URL, if sent in the request.
  38. func (m Message) Referer() string {
  39. return m.req.Referer()
  40. }
  41. func header(w http.ResponseWriter, contentType string) {
  42. w.Header().Set(`Content-Type`, contentType)
  43. w.Header().Set(`X-Powered-By`, sacred.LibName+`/`+sacred.LibVersion)
  44. w.WriteHeader(http.StatusOK)
  45. }
  46. // SetHeader set http response header
  47. func SetHeader(w http.ResponseWriter, key, value string) {
  48. w.Header().Set(key, value)
  49. }
  50. // Redirect redirect
  51. func Redirect(w http.ResponseWriter, r *http.Request, url string) {
  52. //w.Header().Set(`Location`, url)
  53. //w.WriteHeader(http.StatusFound)
  54. http.Redirect(w, r, url, http.StatusFound)
  55. }
  56. // WriteJSON response JSON data.
  57. func WriteJSON(w http.ResponseWriter, response interface{}) error {
  58. header(w, `application/json; charset=utf-8`)
  59. return json.NewEncoder(w).Encode(response)
  60. }
  61. // WriteXML response XML data.
  62. func WriteXML(w http.ResponseWriter, response interface{}) error {
  63. header(w, `application/xml; charset=utf-8`)
  64. return xml.NewEncoder(w).Encode(response)
  65. }
  66. // WriteBytes response bytes
  67. func WriteBytes(w http.ResponseWriter, response interface{}) error {
  68. header(w, `text/html; charset=utf-8`)
  69. _, err := w.Write(response.([]byte))
  70. return err
  71. }