-
Notifications
You must be signed in to change notification settings - Fork 1
/
json.go
36 lines (27 loc) · 988 Bytes
/
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
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
}