Home

ugit @5f408c1fb1ddaa63a3ee9bf239f552bcef9b0778 - refs - log -
-
https://git.jolheiser.com/ugit.git
The code powering this h*ckin' site
ugit / internal / http / httperr / httperr.go
- raw
 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
package httperr

import (
	"errors"
	"net/http"

	"github.com/charmbracelet/log"
)

type httpError struct {
	err    error
	status int
}

func (h httpError) Error() string {
	return h.err.Error()
}

func (h httpError) Unwrap() error {
	return h.err
}

func Error(err error) httpError {
	return Status(err, http.StatusInternalServerError)
}

func Status(err error, status int) httpError {
	return httpError{err: err, status: status}
}

func Handler(fn func(w http.ResponseWriter, r *http.Request) error) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := fn(w, r); err != nil {
			status := http.StatusInternalServerError

			var httpErr httpError
			if errors.As(err, &httpErr) {
				status = httpErr.status
			}

			log.Error(err)
			http.Error(w, http.StatusText(status), status)
		}
	}
}