-
Notifications
You must be signed in to change notification settings - Fork 2
/
response.go
56 lines (46 loc) · 1.56 KB
/
response.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package rest
import (
"encoding/json"
"net/http"
"strconv"
"github.com/grupawp/tensorflow-deploy/app"
"github.com/grupawp/tensorflow-deploy/exterr"
)
func writeJSONSuccessResponse(w http.ResponseWriter, r *http.Request, statusCode int, body interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
if body != nil {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(true)
if err := enc.Encode(body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func writeJSONErrorResponse(w http.ResponseWriter, r *http.Request, statusCode int, err error) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
if err != nil {
preparedError := prepareErrorDetails(err, statusCode)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(true)
if err := enc.Encode(preparedError); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func prepareErrorDetails(err error, errorCode int) app.ErrorBody {
var result app.ErrorBody
result.Error.ErrorCode = strconv.Itoa(errorCode)
result.Error.ErrorMessage = err.Error()
if newErr, ok := err.(*exterr.Error); ok {
result.Error.ErrorMessage = newErr.Error()
}
return result
}
func writeBinaryDataResponse(w http.ResponseWriter, r *http.Request, data []byte, filename string) {
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.Header().Set("Content-Type", "application/octet-stream;")
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
w.Write(data)
}