-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweb.go
40 lines (32 loc) · 831 Bytes
/
web.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
40
package utils
import (
"encoding/json"
"fmt"
"net/http"
)
type WebAPIError struct {
ErrorString string `json:"error"`
ErrorCode int `json:"code"`
}
func NewWebAPIError(code int, errorString string) WebAPIError {
return WebAPIError{
ErrorString: errorString,
ErrorCode: code,
}
}
func WebWrite(w http.ResponseWriter, data interface{}) error {
bs, err := json.Marshal(data)
if err != nil {
fmt.Printf("Error in web write: %s\n", err)
return WebWriteError(w, 500, "internal server error")
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(bs)
return err
}
func WebWriteError(w http.ResponseWriter, code int, errorString string) error {
msg := NewWebAPIError(code, errorString)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
return WebWrite(w, msg)
}