Created
August 31, 2016 03:11
-
-
Save anxiousmodernman/03b25634940fada48ef89a8f15b986f9 to your computer and use it in GitHub Desktop.
Sick HTTP helpers in Go
This file contains hidden or 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
import ( | |
"encoding/json" | |
"log" | |
"net" | |
"net/http" | |
"os" | |
"gopkg.in/mgo.v2" | |
"github.com/rs/cors" | |
"github.com/rs/xaccess" | |
"github.com/rs/xhandler" | |
"github.com/rs/xlog" | |
"github.com/rs/xmux" | |
"golang.org/x/net/context" | |
) | |
func writeJson(w http.ResponseWriter, value interface{}) error { | |
w.Header().Set("Content-Type", "application/json") | |
return json.NewEncoder(w).Encode(value) | |
} | |
func writeError(ctx context.Context, w http.ResponseWriter, err error) { | |
logger := xlog.FromContext(ctx) | |
errStr := err.Error() | |
w.Header().Set("Content-Type", "text/plain") | |
if err == mgo.ErrNotFound { | |
http.Error(w, errStr, http.StatusNotFound) | |
logger.Error(errStr) | |
} else { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
logger.Error(errStr) | |
} | |
} | |
func readJson(w http.ResponseWriter, r *http.Request, value interface{}) (ok bool) { | |
err := json.NewDecoder(r.Body).Decode(value) | |
if err != nil { | |
http.Error(w, err.Error(), 400) | |
return false | |
} else { | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment