aboutsummaryrefslogtreecommitdiff
path: root/internal/webui/utils.go
blob: be8baf373dda18c666e28c188726b1499f655e4a (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
59
60
package webui

import (
	"embed"
	"log"
	"net/http"

	"git.adyxax.org/adyxax/trains/pkg/config"
	"git.adyxax.org/adyxax/trains/pkg/database"
	"git.adyxax.org/adyxax/trains/pkg/navitia_api_client"
)

//go:embed html/*
var templatesFS embed.FS

//go:embed static/*
var staticFS embed.FS

// the environment that will be passed to our handlers
type env struct {
	conf    *config.Config
	dbEnv   *database.DBEnv
	navitia navitia_api_client.Client
}

type handlerError interface {
	error
	Status() int
}

type statusError struct {
	code int
	err  error
}

func (e *statusError) Error() string           { return e.err.Error() }
func (e *statusError) Status() int             { return e.code }
func newStatusError(code int, err error) error { return &statusError{code: code, err: err} }

type handler struct {
	e *env
	h func(e *env, w http.ResponseWriter, r *http.Request) error
}

// ServeHTTP allows our handler type to satisfy http.Handler
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	err := h.h(h.e, w, r)
	if err != nil {
		switch e := err.(type) {
		case handlerError:
			log.Printf("HTTP %d - %s", e.Status(), e)
			http.Error(w, e.Error(), e.Status())
		default:
			// Any error types we don't specifically look out for default to serving a HTTP 500
			log.Printf("%s : handler returned an unexpected error : %+v", path, e)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		}
	}
}