Skip to content

Instantly share code, notes, and snippets.

@elimisteve
Created December 1, 2018 04:29
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 elimisteve/2780dfcb10618001b0c25e005999281c to your computer and use it in GitHub Desktop.
Save elimisteve/2780dfcb10618001b0c25e005999281c to your computer and use it in GitHub Desktop.
Go JSON handlers
package main
import (
"fmt"
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/websocket"
)
const contentTypeJSON = "application/json; charset=utf-8"
func WriteError(w http.ResponseWriter, errStr string, secretErr error) error {
return WriteErrorStatus(w, errStr, secretErr, http.StatusInternalServerError)
}
func WriteErrorStatus(w http.ResponseWriter, errStr string, secretErr error, status int) error {
log.Debugf("Real error: %v", secretErr)
log.Debugf("Returning HTTP %d w/error: %q", status, errStr)
w.Header().Set("Content-Type", contentTypeJSON)
w.WriteHeader(status)
_, err := fmt.Fprintf(w, `{"error":%q}`, errStr)
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment