Created
December 23, 2016 04:09
-
-
Save cyrusn/a97a6891f33a206f8b23cf3bbbba97cb to your computer and use it in GitHub Desktop.
Wirte JSON and Error message for net/http ResponseWriter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jsonAPI | |
import ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
) | |
type MessageResponse struct { | |
Message string `json:"message"` | |
} | |
type JSONWriter interface { | |
Write([]byte) (int, error) | |
WriteHeader(int) | |
Header() http.Header | |
} | |
func WriteJSON(jw JSONWriter, data interface{}, code ...int) { | |
optionalStatusCode(jw, code...) | |
jw.Header().Set("Content-Type", "application/json") | |
var ( | |
b []byte | |
err error | |
) | |
switch t := data.(type) { | |
case []byte: | |
b = t | |
case string: | |
b = []byte(t) | |
default: | |
b, err = json.Marshal(data) | |
if err != nil { | |
WriteError(jw, err) | |
return | |
} | |
} | |
jw.Write(b) | |
} | |
func WriteError(w http.ResponseWriter, message interface{}, code ...int) { | |
var msg string | |
switch m := message.(type) { | |
case string: | |
msg = m | |
case error: | |
msg = m.Error() | |
} | |
w.Header().Set("Content-Type", "application/json") | |
s := fmt.Sprintf(`{"message":"%s"}`, msg) | |
optionalStatusCode(w, code...) | |
w.Write([]byte(s)) | |
} | |
func optionalStatusCode(w http.ResponseWriter, code ...int) { | |
switch len(code) { | |
case 0: | |
default: | |
w.WriteHeader(code[0]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment