Created
July 11, 2017 00:12
-
-
Save nowylie/e6ee4f57378934cbb87d85ea7dbae891 to your computer and use it in GitHub Desktop.
Why not just write a couple of utility functions?
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 main | |
import ( | |
"bytes" | |
"encoding/json" | |
"io" | |
"net/http" | |
) | |
type jsonMessage struct { | |
Message string `json:"msg"` | |
} | |
type jsonError struct { | |
Error string `json:"error"` | |
} | |
func index(w http.ResponseWriter, r *http.Request) { | |
// Return a blank error | |
http.Error(w, "not found", http.StatusNotFound) | |
// Return a JSON error | |
serveJSON(w, jsonError{"not found"}, http.StatusNotFound) | |
// Return plain text | |
contentType(w, "text/plain") | |
serveBytes(w, []byte("test"), http.StatusOK) | |
// Return html | |
contentType(w, "text/html") | |
serveBytes(w, []byte("<h1>test</h1>"), http.StatusOK) | |
// Return JSON data | |
serveJSON(w, jsonMessage{"test"}, http.StatusOK) | |
// Return a generic reader | |
b := bytes.NewBufferString("test") | |
contentType(w, "text/plain") | |
serveReader(w, b, http.StatusOK) | |
} | |
func contentType(w http.ResponseWriter, t string) { | |
w.Header().Set("Content-Type", t) | |
} | |
func serveJSON(w http.ResponseWriter, content interface{}, status int) { | |
b, err := json.Marshal(content) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
w.Header().Set("Content-Type", "application/json") | |
w.WriteHeader(status) | |
w.Write(b) | |
} | |
func serveBytes(w http.ResponseWriter, content []byte, status int) { | |
w.WriteHeader(status) | |
w.Write(content) | |
} | |
func serveReader(w http.ResponseWriter, content io.Reader, status int) { | |
w.WriteHeader(status) | |
io.Copy(w, content) | |
} | |
func serveText(w http.ResponseWriter, content []byte, status int) { | |
w.Header().Set("Content-Type", "text/plain") | |
w.WriteHeader(status) | |
w.Write(content) | |
} | |
func main() { | |
http.Handle("/test", http.HandlerFunc(index)) | |
http.ListenAndServe(":8081", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment