mirror of
https://github.com/lus/pasty.git
synced 2023-08-10 21:13:09 +03:00
Fix frontend routing
This commit is contained in:
10
internal/web/logger.go
Normal file
10
internal/web/logger.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package web
|
||||
|
||||
// nilLogger represents a logger that does not print anything
|
||||
type nilLogger struct {
|
||||
}
|
||||
|
||||
// Printf prints nothing
|
||||
func (logger *nilLogger) Printf(string, ...interface{}) {
|
||||
return
|
||||
}
|
@@ -5,6 +5,8 @@ import (
|
||||
v1 "github.com/Lukaesebrot/pasty/internal/web/controllers/v1"
|
||||
routing "github.com/fasthttp/router"
|
||||
"github.com/valyala/fasthttp"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Serve serves the web server
|
||||
@@ -12,6 +14,23 @@ func Serve() error {
|
||||
// Create the router
|
||||
router := routing.New()
|
||||
|
||||
// Define the 404 handler
|
||||
router.NotFound = func(ctx *fasthttp.RequestCtx) {
|
||||
ctx.SetStatusCode(fasthttp.StatusNotFound)
|
||||
ctx.SetBodyString("not found")
|
||||
}
|
||||
|
||||
// Route the frontend requests
|
||||
frontend := frontendHandler()
|
||||
router.GET("/{path:*}", func(ctx *fasthttp.RequestCtx) {
|
||||
path := string(ctx.Path())
|
||||
if !strings.HasPrefix(path, "/api") {
|
||||
frontend(ctx)
|
||||
return
|
||||
}
|
||||
router.NotFound(ctx)
|
||||
})
|
||||
|
||||
// Route the API endpoints
|
||||
apiRoute := router.Group("/api")
|
||||
{
|
||||
@@ -21,9 +40,24 @@ func Serve() error {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Route the paste endpoints
|
||||
|
||||
// Serve the web server
|
||||
address := env.Get("WEB_ADDRESS", ":8080")
|
||||
return fasthttp.ListenAndServe(address, router.Handler)
|
||||
return (&fasthttp.Server{
|
||||
Handler: router.Handler,
|
||||
Logger: new(nilLogger),
|
||||
}).ListenAndServe(address)
|
||||
}
|
||||
|
||||
// frontendHandler handles the frontend routing
|
||||
func frontendHandler() fasthttp.RequestHandler {
|
||||
// Create the file server
|
||||
fs := &fasthttp.FS{
|
||||
Root: "./web",
|
||||
IndexNames: []string{"index.html"},
|
||||
CacheDuration: 0,
|
||||
}
|
||||
fs.PathNotFound = func(ctx *fasthttp.RequestCtx) {
|
||||
ctx.SendFile(filepath.Join(fs.Root, "index.html"))
|
||||
}
|
||||
return fs.NewRequestHandler()
|
||||
}
|
||||
|
Reference in New Issue
Block a user