Core functionality for new aiterp.net servers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.4 KiB

7 years ago
7 years ago
7 years ago
7 years ago
  1. package response
  2. import (
  3. "compress/gzip"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "strings"
  9. )
  10. // JSON makes a JSON response
  11. func JSON(writer http.ResponseWriter, status int, data interface{}) {
  12. jsonData, err := json.Marshal(data)
  13. if err != nil {
  14. log.Println("JSON Marshal failed: ", err.Error())
  15. writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
  16. writer.WriteHeader(503)
  17. fmt.Fprint(writer, "JSON marshalling failed:", err.Error())
  18. return
  19. }
  20. writer.Header().Set("Content-Type", "application/json")
  21. writer.WriteHeader(status)
  22. writer.Write(jsonData)
  23. }
  24. // CompressedJSON makes a compressed JSON response, but only if the client supports it and the.
  25. // payload exceeds 1024 bytes.
  26. func CompressedJSON(writer http.ResponseWriter, request *http.Request, status int, data interface{}) {
  27. jsonData, err := json.Marshal(data)
  28. if err != nil {
  29. log.Println("JSON Marshal failed: ", err.Error())
  30. writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
  31. writer.WriteHeader(503)
  32. fmt.Fprint(writer, "JSON marshalling failed:", err.Error())
  33. return
  34. }
  35. writer.Header().Set("Content-Type", "application/json")
  36. if len(jsonData) > 1024 && strings.Contains(request.Header.Get("Accept-Encoding"), "gzip") {
  37. writer.Header().Set("Content-Encoding", "gzip")
  38. writer.WriteHeader(status)
  39. gz := gzip.NewWriter(writer)
  40. gz.Write(jsonData)
  41. gz.Close()
  42. } else {
  43. writer.WriteHeader(status)
  44. writer.Write(jsonData)
  45. }
  46. }