Add custom static links (#234)

This commit is contained in:
Thomas Miceli
2024-04-02 17:12:54 +02:00
parent c185cb8933
commit 3f5f4e01f1
7 changed files with 209 additions and 52 deletions

View File

@ -7,6 +7,7 @@ import (
"fmt"
"github.com/thomiceli/opengist/internal/index"
"github.com/thomiceli/opengist/internal/utils"
"github.com/thomiceli/opengist/templates"
htmlpkg "html"
"html/template"
"io"
@ -30,7 +31,6 @@ import (
"github.com/thomiceli/opengist/internal/git"
"github.com/thomiceli/opengist/internal/i18n"
"github.com/thomiceli/opengist/public"
"github.com/thomiceli/opengist/templates"
"golang.org/x/text/language"
)
@ -138,6 +138,10 @@ var (
},
"addMetadataToSearchQuery": addMetadataToSearchQuery,
"indexEnabled": index.Enabled,
"isUrl": func(s string) bool {
_, err := url.ParseRequestURI(s)
return err == nil
},
}
)
@ -186,9 +190,22 @@ func NewServer(isDev bool) *Server {
e.Use(middleware.Recover())
e.Use(middleware.Secure())
e.Renderer = &Template{
templates: template.Must(template.New("t").Funcs(fm).ParseFS(templates.Files, "*/*.html")),
t := template.Must(template.New("t").Funcs(fm).ParseFS(templates.Files, "*/*.html"))
customPattern := filepath.Join(config.GetHomeDir(), "custom", "*.html")
matches, err := filepath.Glob(customPattern)
if err != nil {
log.Fatal().Err(err).Msg("Failed to check for custom templates")
}
if len(matches) > 0 {
t, err = t.ParseGlob(customPattern)
if err != nil {
log.Fatal().Err(err).Msg("Failed to parse custom templates")
}
}
e.Renderer = &Template{
templates: t,
}
e.HTTPErrorHandler = func(er error, ctx echo.Context) {
if err, ok := er.(*echo.HTTPError); ok {
if err.Code >= 500 {
@ -211,14 +228,6 @@ func NewServer(isDev bool) *Server {
if !dev {
parseManifestEntries()
}
customFs := os.DirFS(filepath.Join(config.GetHomeDir(), "custom"))
e.GET("/assets/*", func(c echo.Context) error {
if _, err := public.Files.Open(path.Join("assets", c.Param("*"))); !dev && err == nil {
return echo.WrapHandler(http.FileServer(http.FS(public.Files)))(c)
}
return echo.WrapHandler(http.StripPrefix("/assets/", http.FileServer(http.FS(customFs))))(c)
})
// Web based routes
g1 := e.Group("")
@ -309,6 +318,23 @@ func NewServer(isDev bool) *Server {
}
}
customFs := os.DirFS(filepath.Join(config.GetHomeDir(), "custom"))
e.GET("/assets/*", func(ctx echo.Context) error {
if _, err := public.Files.Open(path.Join("assets", ctx.Param("*"))); !dev && err == nil {
return echo.WrapHandler(http.FileServer(http.FS(public.Files)))(ctx)
}
// if the custom file is an .html template, render it
if strings.HasSuffix(ctx.Param("*"), ".html") {
if err := html(ctx, ctx.Param("*")); err != nil {
return notFound("Page not found")
}
return nil
}
return echo.WrapHandler(http.StripPrefix("/assets/", http.FileServer(http.FS(customFs))))(ctx)
})
// Git HTTP routes
if config.C.HttpGit {
e.Any("/:user/:gistname/*", gitHttp, gistSoftInit)