response.go 975 B

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