json.go 836 B

12345678910111213141516171819202122232425262728293031323334
  1. package util
  2. import (
  3. "compress/gzip"
  4. "encoding/json"
  5. "net/http"
  6. "strings"
  7. )
  8. func Json(fn func(http.ResponseWriter, *http.Request) Return) http.Handler {
  9. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  10. // w.Header().Set("Content-Type", "application/json")
  11. // if r.Method == "OPTIONS" {
  12. // WriteResponse(w, http.StatusOK, "Ok", "Ok")
  13. // return
  14. // }
  15. var rt interface{}
  16. var enc *json.Encoder
  17. if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  18. rt = fn(w, r)
  19. enc = json.NewEncoder(w)
  20. } else {
  21. w.Header().Set("Content-Encoding", "gzip")
  22. gz := gzip.NewWriter(w)
  23. defer gz.Close()
  24. rt = fn(w, r)
  25. enc = json.NewEncoder(gz)
  26. }
  27. // Encode result
  28. if err := enc.Encode(&rt); nil != err {
  29. WriteResponse(w, http.StatusBadRequest, "Error", err.Error())
  30. }
  31. })
  32. }