From 865ce6f80ef44fa466c360672280cc43cba7cfa5 Mon Sep 17 00:00:00 2001 From: Gisle Aune Date: Sun, 13 Aug 2017 16:21:07 +0200 Subject: [PATCH] Fixed path crash in static (same as resource), Added CompressedJSON response type. --- response/json.go | 32 ++++++++++++++++++++++++++++++++ static.go | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/response/json.go b/response/json.go index 53cabc2..692f849 100644 --- a/response/json.go +++ b/response/json.go @@ -1,10 +1,12 @@ package response import ( + "compress/gzip" "encoding/json" "fmt" "log" "net/http" + "strings" ) // 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.WriteHeader(status) + 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) + } +} diff --git a/static.go b/static.go index 9b3bea7..6e0989d 100644 --- a/static.go +++ b/static.go @@ -22,7 +22,7 @@ func NewStatic(path string) *Static { func (static *Static) Handle(urlPath string, w http.ResponseWriter, req *http.Request, user *auth.User) bool { // Get the subpath out of the path subpath := req.URL.Path[len(urlPath):] - if subpath[0] == '/' { + if len(subpath) > 0 && subpath[0] == '/' { subpath = subpath[1:] }