Skip to content

Instantly share code, notes, and snippets.

@richardprice
Created February 22, 2020 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardprice/48973dfe0cbc0b4bc627d432602dcd25 to your computer and use it in GitHub Desktop.
Save richardprice/48973dfe0cbc0b4bc627d432602dcd25 to your computer and use it in GitHub Desktop.
package handlers
import (
"encoding/json"
"net/http"
)
type Pageable struct {
Total int
Items interface{}
}
func UnauthorisedResponse(w http.ResponseWriter) {
w.WriteHeader(http.StatusUnauthorized)
}
func NotFoundResponse(w http.ResponseWriter) {
w.WriteHeader(http.StatusNotFound)
}
func OkResponse(w http.ResponseWriter, content interface{}) {
ResponseWithBody(w, content)
w.WriteHeader(http.StatusOK)
}
func EmptyResponse(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}
func BadRequestResponse(w http.ResponseWriter, content interface{}) {
ResponseWithBody(w, content)
w.WriteHeader(http.StatusBadRequest)
}
func CreatedResponse(w http.ResponseWriter, content interface{}) {
ResponseWithBody(w, content)
w.WriteHeader(http.StatusCreated)
}
func ServerErrorResponse(w http.ResponseWriter) {
w.WriteHeader(http.StatusInternalServerError)
}
func ResponseWithBody(w http.ResponseWriter, content interface{}) {
w.Header().Set("Content-Type", "application/json")
var payload []byte
if content != nil {
payload, _ = json.Marshal(content)
} else {
payload = []byte("{}")
}
w.Write(payload)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment