gitstack

grindlemire/gothem-stack code browser

1.4 KB Go 64 lines 2025-11-29 · 98bbe10 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package router

import (
	"context"
	"net/http"

	"github.com/grindlemire/gothem-stack/pkg/auth"
	"github.com/grindlemire/gothem-stack/pkg/handler"
	"github.com/grindlemire/gothem-stack/web"

	"github.com/grindlemire/graft"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/pkg/errors"
)

const ID = graft.ID("router")

type Output struct {
	http.Handler
}

func init() {
	graft.Register(graft.Node[Output]{
		ID:        ID,
		Cacheable: true,
		Run:       run,
	})
}

func run(ctx context.Context) (Output, error) {
	e := echo.New()

	e.Use(
		// recover from panics and create errors from them
		middleware.Recover(),
		// other global middleware goes here
	)

	// register the customer pages and components
	homeHandler, err := handler.NewHomeHandler()
	if err != nil {
		return Output{}, err
	}
	homeHandler.RegisterRoutes(
		e.Group("", auth.Middleware()),
	)

	// register the static assets like the favicon and the css
	err = web.RegisterStaticAssets(e)
	if err != nil {
		return Output{}, err
	}

	// all other routes should return not found. This should be the last registered route in the list
	e.HTTPErrorHandler = handler.Error
	e.Add(echo.RouteNotFound, "/*", echo.HandlerFunc(func(c echo.Context) error {
		return echo.ErrNotFound.SetInternal(errors.Errorf("not found | uri=[%s]", c.Request().RequestURI))
	}), []echo.MiddlewareFunc{}...)

	return Output{
		Handler: e.Server.Handler,
	}, nil
}