/
core.go
81 lines (68 loc) · 2.34 KB
/
core.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
package core
import (
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/render"
"github.com/go-pg/pg/v10"
)
//Handler consists of the DB connection and Routes
type Handler struct {
DB *pg.DB
Routes *chi.Mux
Tx *pg.Tx
}
//ErrResponse contains error information
type ErrResponse struct {
Err error `json:"-"` // low-level runtime error
HTTPStatusCode int `json:"-"` // http response status code
StatusText string `json:"status"` // user-level status message
AppCode int64 `json:"code,omitempty"` // application-specific error code
ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
}
//Render response writer
func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {
render.Status(r, e.HTTPStatusCode)
return nil
}
//ErrInvalidRequest – The request was unacceptable, often due to missing a required parameter.
func ErrInvalidRequest(err error) render.Renderer {
return &ErrResponse{
Err: err,
HTTPStatusCode: 400,
StatusText: "Invalid Request",
ErrorText: err.Error(),
}
}
//ErrUnauthorized – No valid API token provided.
var ErrUnauthorized = &ErrResponse{HTTPStatusCode: 401, StatusText: "Unauthorized"}
//ErrRequestFailed – The parameters were valid but the request failed.
func ErrRequestFailed(err error) render.Renderer {
return &ErrResponse{
Err: err,
HTTPStatusCode: 402,
StatusText: "Request Failed",
ErrorText: err.Error(),
}
}
//ErrNotFound – The requested resource doesn't exist.
var ErrNotFound = &ErrResponse{HTTPStatusCode: 404, StatusText: "Not Found"}
//ErrConflict – The request conflicts with another request (perhaps due to using the same idempotent key).
func ErrConflict(err error) render.Renderer {
return &ErrResponse{
Err: err,
HTTPStatusCode: 409,
StatusText: "Conflict",
ErrorText: err.Error(),
}
}
//ErrRender response error writer
func ErrRender(err error) render.Renderer {
return &ErrResponse{
Err: err,
HTTPStatusCode: 422,
StatusText: "Error rendering response.",
ErrorText: err.Error(),
}
}
//ErrTooManyRequests – Too many requests hit the API too quickly. We recommend an exponential backoff of your requests.
var ErrTooManyRequests = &ErrResponse{HTTPStatusCode: 429, StatusText: "Too Many Requests"}