|
@ -1,10 +1,12 @@ |
|
|
package response |
|
|
package response |
|
|
|
|
|
|
|
|
import ( |
|
|
import ( |
|
|
|
|
|
"compress/gzip" |
|
|
"encoding/json" |
|
|
"encoding/json" |
|
|
"fmt" |
|
|
"fmt" |
|
|
"log" |
|
|
"log" |
|
|
"net/http" |
|
|
"net/http" |
|
|
|
|
|
"strings" |
|
|
) |
|
|
) |
|
|
|
|
|
|
|
|
// JSON makes a JSON response
|
|
|
// JSON makes a JSON response
|
|
@ -22,5 +24,35 @@ func JSON(writer http.ResponseWriter, status int, data interface{}) { |
|
|
|
|
|
|
|
|
writer.Header().Set("Content-Type", "application/json") |
|
|
writer.Header().Set("Content-Type", "application/json") |
|
|
writer.WriteHeader(status) |
|
|
writer.WriteHeader(status) |
|
|
|
|
|
|
|
|
writer.Write(jsonData) |
|
|
writer.Write(jsonData) |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
// CompressedJSON makes a compressed JSON response, but only if the client supports it and the.
|
|
|
|
|
|
// payload exceeds 1024 bytes.
|
|
|
|
|
|
func CompressedJSON(writer http.ResponseWriter, request *http.Request, status int, data interface{}) { |
|
|
|
|
|
jsonData, err := json.Marshal(data) |
|
|
|
|
|
|
|
|
|
|
|
if err != nil { |
|
|
|
|
|
log.Println("JSON Marshal failed: ", err.Error()) |
|
|
|
|
|
|
|
|
|
|
|
writer.Header().Set("Content-Type", "text/plain; charset=utf-8") |
|
|
|
|
|
writer.WriteHeader(503) |
|
|
|
|
|
fmt.Fprint(writer, "JSON marshalling failed:", err.Error()) |
|
|
|
|
|
return |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
writer.Header().Set("Content-Type", "application/json") |
|
|
|
|
|
|
|
|
|
|
|
if len(jsonData) > 1024 && strings.Contains(request.Header.Get("Accept-Encoding"), "gzip") { |
|
|
|
|
|
writer.Header().Set("Content-Encoding", "gzip") |
|
|
|
|
|
writer.WriteHeader(status) |
|
|
|
|
|
|
|
|
|
|
|
gz := gzip.NewWriter(writer) |
|
|
|
|
|
gz.Write(jsonData) |
|
|
|
|
|
gz.Close() |
|
|
|
|
|
} else { |
|
|
|
|
|
writer.WriteHeader(status) |
|
|
|
|
|
writer.Write(jsonData) |
|
|
|
|
|
} |
|
|
|
|
|
} |