BlueGit

timfa bluegit

Files

bluegit / internal / server / operr.go

operr.go

feat: bied dezelfde acties als de UI aan via /api/v1
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
d89195e9 History
operr.go 1.9 KiB Download Raw
1package server
2
3import (
4 "errors"
5 "net/http"
6
7 "gitlab.com/Timfa/bluegit/internal/i18n"
8 "gitlab.com/Timfa/bluegit/internal/store"
9)
10
11// opError is een fout uit de gedeelde servicelaag, met een HTTP-status.
12type opError struct {
13 status int
14 err error
15}
16
17func (e *opError) Error() string {
18 if e == nil || e.err == nil {
19 return ""
20 }
21 return e.err.Error()
22}
23
24func (e *opError) Unwrap() error {
25 if e == nil {
26 return nil
27 }
28 return e.err
29}
30
31func fail(status int, err error) error {
32 if err == nil {
33 err = errors.New(http.StatusText(status))
34 }
35 return &opError{status: status, err: err}
36}
37
38func statusOf(err error) int {
39 var oe *opError
40 if errors.As(err, &oe) && oe.status != 0 {
41 return oe.status
42 }
43 if store.IsNotFound(err) {
44 return http.StatusNotFound
45 }
46 return http.StatusBadRequest
47}
48
49func (s *Server) uiOK(w http.ResponseWriter, r *http.Request, back string, err error) bool {
50 if err == nil {
51 return true
52 }
53 st := statusOf(err)
54 if st == http.StatusNotFound {
55 http.NotFound(w, r)
56 return false
57 }
58 if st == http.StatusForbidden || st == http.StatusUnauthorized || st == http.StatusInternalServerError {
59 http.Error(w, s.trErr(r, err), st)
60 return false
61 }
62 s.redirect(w, r, back, "", s.commitProblem(r, err))
63 return false
64}
65
66func (s *Server) uiFail(w http.ResponseWriter, r *http.Request, back string, err error) {
67 st := statusOf(err)
68 if st == http.StatusForbidden || st == http.StatusUnauthorized || st == http.StatusInternalServerError {
69 http.Error(w, s.trErr(r, err), st)
70 return
71 }
72 s.redirect(w, r, back, "", s.trErr(r, err))
73}
74
75func userEmail(name string) string {
76 return name + "@users.git.timfalken.com"
77}
78
79func notFound(err error) error {
80 if err == nil {
81 return fail(http.StatusNotFound, i18n.E("err.notFound"))
82 }
83 if store.IsNotFound(err) {
84 return fail(http.StatusNotFound, i18n.E("err.notFound"))
85 }
86 return fail(http.StatusBadRequest, err)
87}