github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/easy/ezhttp/response.go (about) 1 package ezhttp 2 3 import ( 4 "net/http" 5 6 "github.com/jxskiss/gopkg/v2/perf/json" 7 ) 8 9 var ( 10 newlineBytes = []byte{'\n'} 11 12 rspFailedMarshalJSON = []byte("Failed to marshal JSON data.") 13 ) 14 15 // JSON serializes the given data as JSON into the response body. 16 // It also sets the Content-Type as "application/json". 17 func JSON(w http.ResponseWriter, statusCode int, data any) { 18 jsonBuf, err := json.Marshal(data) 19 if err != nil { 20 w.WriteHeader(http.StatusInternalServerError) 21 w.Write(rspFailedMarshalJSON) 22 return 23 } 24 w.Header().Set(hdrContentTypeKey, contentTypeJSON) 25 w.WriteHeader(statusCode) 26 w.Write(jsonBuf) 27 } 28 29 // JSONHumanFriendly serializes the given data as pretty JSON (indented + newlines) 30 // into the response body. 31 // It also sets the Content-Type as "application/json". 32 // 33 // WARNING: we recommend using this only for development purposes 34 // since printing pretty JSON is more CPU and bandwidth consuming. 35 // Use JSON() instead. 36 func JSONHumanFriendly(w http.ResponseWriter, statusCode int, data any) { 37 jsonBuf, err := json.HumanFriendly.MarshalIndent(data, "", " ") 38 if err != nil { 39 w.WriteHeader(http.StatusInternalServerError) 40 w.Write(rspFailedMarshalJSON) 41 return 42 } 43 addNewline := false 44 if len(jsonBuf) > 0 && jsonBuf[len(jsonBuf)-1] != '\n' { 45 addNewline = true 46 } 47 w.Header().Set(hdrContentTypeKey, contentTypeJSON) 48 w.WriteHeader(statusCode) 49 w.Write(jsonBuf) 50 if addNewline { 51 w.Write(newlineBytes) 52 } 53 }