response.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package myth
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. "net/http"
  6. )
  7. func header(w http.ResponseWriter, contentType string) {
  8. w.Header().Set(`Content-Type`, contentType)
  9. w.Header().Set(`X-Powered-By`, LibName+`/`+LibVersion)
  10. w.WriteHeader(http.StatusOK)
  11. }
  12. // SetHeader set http response header
  13. func SetHeader(w http.ResponseWriter, key, value string) {
  14. w.Header().Set(key, value)
  15. }
  16. // Redirect redirect
  17. func Redirect(w http.ResponseWriter, r *http.Request, url string) {
  18. //w.Header().Set(`Location`, url)
  19. //w.WriteHeader(http.StatusFound)
  20. http.Redirect(w, r, url, http.StatusFound)
  21. }
  22. // WriteJSON response JSON data.
  23. func WriteJSON(w http.ResponseWriter, response interface{}) error {
  24. header(w, `application/json; charset=utf-8`)
  25. return json.NewEncoder(w).Encode(response)
  26. }
  27. // WriteXML response XML data.
  28. func WriteXML(w http.ResponseWriter, response interface{}) error {
  29. header(w, `application/xml; charset=utf-8`)
  30. return xml.NewEncoder(w).Encode(response)
  31. }
  32. // WriteBytes response bytes
  33. func WriteBytes(w http.ResponseWriter, response interface{}) error {
  34. header(w, `text/html; charset=utf-8`)
  35. _, err := w.Write(response.([]byte))
  36. return err
  37. }