-
Notifications
You must be signed in to change notification settings - Fork 1
/
response.go
53 lines (46 loc) · 1.48 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
package model
import (
"github.com/gofiber/fiber/v2"
"github.com/oidc-mytoken/api/v0"
"github.com/valyala/fasthttp"
"github.com/oidc-mytoken/server/internal/utils/errorfmt"
"github.com/oidc-mytoken/server/shared/model"
)
// Response models a http server response
type Response struct {
// The Http Status code of the response
Status int
// The response body, will be marshalled as json
Response interface{}
// Cookies that should be set
Cookies []*fiber.Cookie
}
// Send sends this response using the passed fiber.Ctx
func (r Response) Send(ctx *fiber.Ctx) error {
for _, c := range r.Cookies {
ctx.Cookie(c)
}
if fasthttp.StatusCodeIsRedirect(r.Status) {
return ctx.Redirect(r.Response.(string), r.Status)
}
return ctx.Status(r.Status).JSON(r.Response)
}
// ErrorToInternalServerErrorResponse creates an internal server error response from a golang error
func ErrorToInternalServerErrorResponse(err error) *Response {
return &Response{
Status: fiber.StatusInternalServerError,
Response: model.InternalServerError(errorfmt.Error(err)),
}
}
// ErrorToBadRequestErrorResponse creates a bad request error response from a golang error
func ErrorToBadRequestErrorResponse(err error) *Response {
return &Response{
Status: fiber.StatusBadRequest,
Response: model.BadRequestError(errorfmt.Error(err)),
}
}
// ResponseNYI is the server response when something is not yet implemented
var ResponseNYI = Response{
Status: fiber.StatusNotImplemented,
Response: api.ErrorNYI,
}