github.com/lucasscarioca/music-stash@v0.0.0-20230829021135-a8b8893b12a5/internal/routes/routes.go (about)

     1  package routes
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/labstack/echo/v4"
     8  	"github.com/lucasscarioca/music-stash/internal/controllers"
     9  	"github.com/lucasscarioca/music-stash/internal/routes/middlewares"
    10  	"github.com/lucasscarioca/music-stash/internal/views"
    11  )
    12  
    13  func Mount(e *echo.Echo) {
    14  	e.HTTPErrorHandler = customHTTPErrorHandler
    15  	e.Renderer = views.WithTemplateRegistry()
    16  
    17  	e.GET("ping", pingHandler)
    18  
    19  	// Pages Routes
    20  	pages := e.Group("/", middlewares.CacheControl(0))
    21  	pages.GET("", controllers.Home)
    22  	pages.GET("404", pageNotFoundHandler)
    23  
    24  	// Htmx Fragments Routes
    25  	// hx := e.Group("/hx", middlewares.CacheControl(0), middlewares.ValidateHxRequest)
    26  }
    27  
    28  func customHTTPErrorHandler(err error, c echo.Context) {
    29  	code := http.StatusInternalServerError
    30  	if he, ok := err.(*echo.HTTPError); ok {
    31  		code = he.Code
    32  	}
    33  	host := c.Request().Host
    34  	URI := c.Request().RequestURI
    35  	qs := c.QueryString()
    36  
    37  	c.Logger().Error(err, fmt.Sprintf("\non: %s%s%s error code: %d", host, URI, qs, code))
    38  	if code == 404 {
    39  		c.Redirect(http.StatusTemporaryRedirect, "/404")
    40  	}
    41  	c.String(code, fmt.Sprintf("error code: %d", code))
    42  }
    43  
    44  func pingHandler(c echo.Context) error {
    45  	return c.String(http.StatusOK, "pong")
    46  }
    47  
    48  // TODO: Test Redirect and handler
    49  func pageNotFoundHandler(c echo.Context) error {
    50  	return c.Render(http.StatusOK, "pageNotFound", map[string]any{})
    51  }