-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
82 lines (74 loc) · 1.74 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package webserver
import (
"net/http"
"reflect"
"strconv"
)
// These are the constants used by the HTTP modules
const (
ContentTypeJSON = "application/json; charset=utf-8"
)
type skipResponseHandlingDummy struct{}
var typeOfSkipResponseHandling = reflect.TypeOf(skipResponseHandlingDummy{})
// SkipResponseHandling indicates to the library to skip operating on the HTTP response writer
func SkipResponseHandling() (interface{}, error) {
return skipResponseHandlingDummy{}, nil
}
func shouldSkipHandling(
responseObject interface{},
responseError error,
) bool {
if responseError != nil {
return false
}
var responseType = reflect.TypeOf(responseObject)
return responseType == typeOfSkipResponseHandling
}
func constructResponse(
session *session,
responseObject interface{},
responseError error,
) (int, string) {
if responseError != nil {
return session.customization.InterpretError(
responseError,
)
}
return session.customization.InterpretSuccess(
responseObject,
)
}
// writeResponse responds to the consumer with corresponding HTTP status code and response body
func writeResponse(
session *session,
responseObject interface{},
responseError error,
) {
if shouldSkipHandling(
responseObject,
responseError,
) {
logEndpointResponse(
session,
"None",
"-1",
"Skipped response handling",
)
return
}
var statusCode, responseMessage = constructResponse(
session,
responseObject,
responseError,
)
logEndpointResponse(
session,
http.StatusText(statusCode),
strconv.Itoa(statusCode),
responseMessage,
)
var responseWriter = session.GetResponseWriter()
responseWriter.Header().Set("Content-Type", ContentTypeJSON)
responseWriter.WriteHeader(statusCode)
responseWriter.Write([]byte(responseMessage))
}