Home

ugit @22cdff623a8ec2342b9f90cc60f4d66f0e7ec712 - 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
46
47
48
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
}

// Error returns a generic 500 error
func Error(err error) httpError {
	return Status(err, http.StatusInternalServerError)
}

// Status returns a set status with the error
func Status(err error, status int) httpError {
	return httpError{err: err, status: status}
}

// Handler transforms an http handler + error into a stdlib handler
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)
		}
	}
}