12345678910111213141516171819202122232425262728293031323334 |
- package util
- import (
- "compress/gzip"
- "encoding/json"
- "net/http"
- "strings"
- )
- func Json(fn func(http.ResponseWriter, *http.Request) Return) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // w.Header().Set("Content-Type", "application/json")
- // if r.Method == "OPTIONS" {
- // WriteResponse(w, http.StatusOK, "Ok", "Ok")
- // return
- // }
- var rt interface{}
- var enc *json.Encoder
- if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
- rt = fn(w, r)
- enc = json.NewEncoder(w)
- } else {
- w.Header().Set("Content-Encoding", "gzip")
- gz := gzip.NewWriter(w)
- defer gz.Close()
- rt = fn(w, r)
- enc = json.NewEncoder(gz)
- }
- // Encode result
- if err := enc.Encode(&rt); nil != err {
- WriteResponse(w, http.StatusBadRequest, "Error", err.Error())
- }
- })
- }
|