response.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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, url string) {
  18. w.Header().Set(`Location`, url)
  19. w.WriteHeader(http.StatusFound)
  20. }
  21. // WriteJSON response JSON data.
  22. func WriteJSON(w http.ResponseWriter, response interface{}) error {
  23. header(w, `application/json; charset=utf-8`)
  24. return json.NewEncoder(w).Encode(response)
  25. }
  26. // WriteXML response XML data.
  27. func WriteXML(w http.ResponseWriter, response interface{}) error {
  28. header(w, `application/xml; charset=utf-8`)
  29. return xml.NewEncoder(w).Encode(response)
  30. }
  31. // WriteBytes response bytes
  32. func WriteBytes(w http.ResponseWriter, response interface{}) error {
  33. header(w, `text/html; charset=utf-8`)
  34. _, err := w.Write(response.([]byte))
  35. return err
  36. }