aboutsummaryrefslogtreecommitdiff
path: root/pkg/ext/responses.go
blob: 73543951024733b067f4349abded14992d618f34 (plain)
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
package ext

import (
	"bytes"
	"fmt"

	"github.com/valyala/fasthttp"

	"git.sr.ht/~gabrielgio/img"
)

var (
	ContentTypeJSON     = []byte("application/json")
	ContentTypeHTML     = []byte("text/html")
	ContentTypeMARKDOWN = []byte("text/markdown")
	ContentTypeJPEG     = []byte("image/jpeg")
)

func NotFoundHTML(ctx *fasthttp.RequestCtx) {
	ctx.Response.Header.SetContentType("text/html")
	//nolint:errcheck
	img.Render(ctx, "error.html", &img.HTMLView[string]{
		Data: "NotFound",
	})
}

func NotFound(ctx *fasthttp.RequestCtx) {
	ctx.Response.SetStatusCode(404)
	ct := ctx.Response.Header.ContentType()
	if bytes.Equal(ct, ContentTypeHTML) {
		NotFoundHTML(ctx)
	}
}

func InternalServerError(ctx *fasthttp.RequestCtx, err error) {
	ctx.Response.Header.SetContentType("text/html")
	message := fmt.Sprintf("Internal Server Error:\n%+v", err)
	//nolint:errcheck
	respErr := img.Render(ctx, "error.html", &img.HTMLView[string]{
		Data: message,
	})

	if respErr != nil {
		fmt.Println(respErr.Error())
	}
}

func NoContent(ctx *fasthttp.RequestCtx) {
	ctx.Response.SetStatusCode(204)
}