64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
|
package web
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
"regexp"
|
||
|
|
||
|
"codeberg.org/u1f320/filer/db"
|
||
|
"github.com/go-chi/chi/v5"
|
||
|
"github.com/go-chi/chi/v5/middleware"
|
||
|
"github.com/go-chi/cors"
|
||
|
"github.com/rs/zerolog/log"
|
||
|
)
|
||
|
|
||
|
type App struct {
|
||
|
chi.Router
|
||
|
|
||
|
db *db.DB
|
||
|
}
|
||
|
|
||
|
func New(db *db.DB) *App {
|
||
|
r := chi.NewMux()
|
||
|
r.Use(middleware.Recoverer)
|
||
|
r.Use(requestLogger)
|
||
|
r.Use(cors.Handler(cors.Options{
|
||
|
AllowedOrigins: []string{"https://*", "http://*"},
|
||
|
AllowedMethods: []string{"GET", "OPTIONS"},
|
||
|
MaxAge: 300,
|
||
|
}))
|
||
|
|
||
|
app := &App{
|
||
|
Router: r,
|
||
|
db: db,
|
||
|
}
|
||
|
|
||
|
app.Get("/{hash}/{filename}", app.showFile)
|
||
|
app.Post("/upload", app.uploadFile)
|
||
|
|
||
|
return app
|
||
|
}
|
||
|
|
||
|
var portRegex = regexp.MustCompile(`^\d{2,}$`)
|
||
|
|
||
|
func (app *App) Run(ctx context.Context) {
|
||
|
port := os.Getenv("PORT")
|
||
|
if !portRegex.MatchString(port) {
|
||
|
log.Error().Str("port", port).Msg("$PORT is not a valid integer")
|
||
|
return
|
||
|
}
|
||
|
|
||
|
listenAddr := ":" + port
|
||
|
|
||
|
ech := make(chan error)
|
||
|
go func() {
|
||
|
ech <- http.ListenAndServe(listenAddr, app)
|
||
|
}()
|
||
|
|
||
|
log.Info().Str("port", port).Msg("Running server")
|
||
|
if err := <-ech; err != nil {
|
||
|
log.Err(err).Msg("Running server")
|
||
|
}
|
||
|
}
|