Skip to content

Instantly share code, notes, and snippets.

@anxiousmodernman
Created August 31, 2016 03:11
Show Gist options
  • Save anxiousmodernman/03b25634940fada48ef89a8f15b986f9 to your computer and use it in GitHub Desktop.
Save anxiousmodernman/03b25634940fada48ef89a8f15b986f9 to your computer and use it in GitHub Desktop.
Sick HTTP helpers in Go
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