-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_responders.go
68 lines (63 loc) · 2.06 KB
/
http_responders.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
package main
import (
"fmt"
"net/http"
)
// stripe.com/docs/api/errors
//
// 200: Everything worked as expected.
// 400: The request was unacceptable, often due to missing a required parameter.
// 401: No valid API key provided.
// 402: The parameters were valid but the request failed.
// 404: The requested resource doesn't exist.
// 409: The request conflicts with another request.
// 429: Too many requests hit the API too quickly.
// 500: Something went wrong on our end.
//
const (
StatusCodeOK = 200
StatusCodeBadRequest = 400
StatusCodeUnauthorized = 401
StatusCodeRequestFailed = 402
StatusCodeNotFound = 404
StatusCodeConflict = 409
StatusCodeTooManyRequests = 429
StatusCodeServerError = 500
)
var Statuses = map[int]string{
StatusCodeOK: "OK",
StatusCodeBadRequest: "Bad Request",
StatusCodeUnauthorized: "Unauthorized",
StatusCodeRequestFailed: "Request Failed",
StatusCodeNotFound: "Not Found",
StatusCodeConflict: "Conflict",
StatusCodeTooManyRequests: "Too Many Requests",
StatusCodeServerError: "Server Error",
}
var (
RespondOK = NewResponder(StatusCodeOK)
RespondBadRequest = NewResponder(StatusCodeBadRequest)
RespondUnauthorized = NewResponder(StatusCodeUnauthorized)
RespondRequestFailed = NewResponder(StatusCodeRequestFailed)
RespondNotFound = NewResponder(StatusCodeNotFound)
RespondConflict = NewResponder(StatusCodeConflict)
RespondTooManyRequests = NewResponder(StatusCodeTooManyRequests)
RespondServerError = NewResponder(StatusCodeServerError)
)
// Returns a function that responds to an HTTP request.
func NewResponder(statusCode int) func(http.ResponseWriter) {
respond := func(w http.ResponseWriter) {
if statusCode >= 200 && statusCode <= 299 {
w.WriteHeader(statusCode)
return
}
status, ok := Statuses[statusCode]
if !ok {
err := fmt.Errorf("no such status code %d", statusCode)
panic(err)
}
errStr := fmt.Sprintf("%d %s", statusCode, status)
http.Error(w, errStr, statusCode)
}
return respond
}