-
Notifications
You must be signed in to change notification settings - Fork 32
/
json.go
39 lines (29 loc) · 1.01 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Steve Phillips / elimisteve
// 2017.01.16
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
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
}
// WebSockets
func WSWriteError(wsConn *websocket.Conn, errStr string, secretErr error) error {
log.Debugf("WebSocket error: " + secretErr.Error())
wsErr := fmt.Sprintf(`{"error":%q}`, errStr)
err := wsConn.WriteMessage(websocket.TextMessage, []byte(wsErr))
wsConn.Close() // TODO: Will this panic?
return err
}