-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault.go
More file actions
46 lines (39 loc) · 1.88 KB
/
default.go
File metadata and controls
46 lines (39 loc) · 1.88 KB
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
package restapi
import (
"net/http"
"sync/atomic"
)
// defaultAPI holds the package-level [API] returned by [Default]. It is an
// atomic pointer so it can be hot-swapped via [SetDefault] without locks on
// the read path.
var defaultAPI atomic.Pointer[API]
func init() {
defaultAPI.Store(NewAPI(WithErrorRegistry(newDefaultErrorRegistry())))
}
// newDefaultErrorRegistry builds the pre-populated [ErrorRegistry] used by
// the default [API]. Its fallback is [CodeInternal] with HTTP 500, and it
// pre-registers the eight remaining standard HTTP-aligned codes. It panics
// if the static entry list is malformed, which is by construction
// unreachable for the package's own codes but catches future typos.
func newDefaultErrorRegistry() *ErrorRegistry {
fallback := ErrorRegistryEntry{
StatusCode: http.StatusInternalServerError,
ErrorCode: CodeInternal,
Message: "internal error",
}
registry, err := NewErrorRegistry(
fallback,
ErrorRegistryEntry{StatusCode: http.StatusBadRequest, ErrorCode: CodeBadRequest, Message: "bad request"},
ErrorRegistryEntry{StatusCode: http.StatusUnauthorized, ErrorCode: CodeUnauthorized, Message: "unauthorized"},
ErrorRegistryEntry{StatusCode: http.StatusForbidden, ErrorCode: CodeForbidden, Message: "forbidden"},
ErrorRegistryEntry{StatusCode: http.StatusNotFound, ErrorCode: CodeNotFound, Message: "resource not found"},
ErrorRegistryEntry{StatusCode: http.StatusConflict, ErrorCode: CodeConflict, Message: "conflict"},
ErrorRegistryEntry{StatusCode: http.StatusUnprocessableEntity, ErrorCode: CodeValidationFailed, Message: "validation failed"},
ErrorRegistryEntry{StatusCode: http.StatusTooManyRequests, ErrorCode: CodeTooManyRequests, Message: "too many requests"},
ErrorRegistryEntry{StatusCode: http.StatusServiceUnavailable, ErrorCode: CodeUnavailable, Message: "service unavailable"},
)
if err != nil {
panic(err)
}
return registry
}