summary refs log tree commit diff
path: root/vendor/go.mau.fi/util/exhttp/handleerrors.go
blob: d2d37b1207f1e4581b77c22da9bdc7b758467639 (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
51
52
53
54
55
56
57
58
package exhttp

import "net/http"

type ErrorBodyGenerators struct {
	NotFound         func() []byte
	MethodNotAllowed func() []byte
}

func HandleErrors(next http.Handler, gen ErrorBodyGenerators) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		next.ServeHTTP(&bodyOverrider{
			ResponseWriter:                      w,
			statusNotFoundBodyGenerator:         gen.NotFound,
			statusMethodNotAllowedBodyGenerator: gen.MethodNotAllowed,
		}, r)
	})
}

type bodyOverrider struct {
	http.ResponseWriter

	code     int
	override bool

	statusNotFoundBodyGenerator         func() []byte
	statusMethodNotAllowedBodyGenerator func() []byte
}

var _ http.ResponseWriter = (*bodyOverrider)(nil)

func (b *bodyOverrider) WriteHeader(code int) {
	if b.Header().Get("Content-Type") == "text/plain; charset=utf-8" {
		b.Header().Set("Content-Type", "application/json")

		b.override = true
	}

	b.code = code
	b.ResponseWriter.WriteHeader(code)
}

func (b *bodyOverrider) Write(body []byte) (int, error) {
	if b.override {
		switch b.code {
		case http.StatusNotFound:
			if b.statusNotFoundBodyGenerator != nil {
				body = b.statusNotFoundBodyGenerator()
			}
		case http.StatusMethodNotAllowed:
			if b.statusMethodNotAllowedBodyGenerator != nil {
				body = b.statusMethodNotAllowedBodyGenerator()
			}
		}
	}

	return b.ResponseWriter.Write(body)
}