refactor: modularize main function

This commit is contained in:
jabuxas 2024-10-15 22:41:51 -03:00
parent 00d2f3e510
commit 8afc49bd04
2 changed files with 30 additions and 17 deletions

View File

@ -13,6 +13,28 @@ import (
func main() {
app := new(Application)
parseEnv(app)
mux := http.NewServeMux()
setupHandlers(mux, app)
srv := &http.Server{
Addr: app.port,
Handler: mux,
IdleTimeout: 10 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 60 * time.Second,
}
log.Printf("starting server on %s", srv.Addr)
if err := srv.ListenAndServe(); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
func parseEnv(app *Application) {
err := godotenv.Load()
if err != nil {
slog.Warn("no .env file detected, getting env from running process")
@ -25,7 +47,7 @@ func main() {
app.filesDir = os.Getenv("ABYSS_FILEDIR")
app.port = os.Getenv("ABYSS_PORT")
auth := os.Getenv("SHOULD_AUTH")
app.authText = os.Getenv("SHOULD_AUTH")
if app.auth.username == "" {
log.Fatal("basic auth username must be provided")
@ -56,9 +78,11 @@ func main() {
slog.Warn("no root url detected, defaulting to localhost.")
app.url = "localhost" + app.port
}
}
mux := http.NewServeMux()
func setupHandlers(mux *http.ServeMux, app *Application) {
mux.HandleFunc("/", app.indexHandler)
mux.Handle(
"/tree/",
http.StripPrefix(
@ -66,26 +90,14 @@ func main() {
app.basicAuth(app.fileListingHandler),
),
)
mux.HandleFunc("/last", app.lastUploadedHandler)
if auth == "yes" {
if app.authText == "yes" {
mux.HandleFunc("/upload", app.basicAuth(app.uploadHandler))
slog.Warn("text uploading through the browser will be restricted")
} else {
mux.HandleFunc("/upload", app.uploadHandler)
slog.Warn("text uploading through the browser will NOT be restricted")
}
srv := &http.Server{
Addr: app.port,
Handler: mux,
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 60 * time.Second,
}
log.Printf("starting server on %s", srv.Addr)
if err := srv.ListenAndServe(); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}

View File

@ -22,6 +22,7 @@ type Application struct {
key string
filesDir string
port string
authText string
lastUploadedFile string
}