passed/main.go
2024-10-30 16:57:52 +01:00

86 lines
1.7 KiB
Go

package main
import (
"embed"
"encoding/base64"
"log"
"net/http"
"os"
"strconv"
"time"
"git.1e99.eu/1e99/passed/middlewares"
"git.1e99.eu/1e99/passed/routes"
"git.1e99.eu/1e99/passed/storage"
)
//go:embed static/*
var embedFS embed.FS
func run() error {
storage, err := storage.NewStore()
if err != nil {
return err
}
clearIntervalString := os.Getenv("STORE_CLEAR_EXPIRED_INTERVAL")
if clearIntervalString == "" {
log.Printf("No STORE_CLEAR_EXPIRED_INTERVAL provided, defaulting to 30 seconds.")
clearIntervalString = "30"
}
clearInterval, err := strconv.ParseInt(clearIntervalString, 10, 64)
if err != nil {
log.Printf("STORE_CLEAR_EXPIRED_INTERVAL is not a number.")
clearInterval = 30
}
go func() {
ticker := time.Tick(time.Duration(clearInterval) * time.Second)
for {
<-ticker
err := storage.ClearExpired()
if err != nil {
log.Printf("Failed to clear expired passwords: %s", err)
continue
}
log.Printf("Cleared expired passwords.")
}
}()
mux := http.NewServeMux()
mux.Handle("GET /", routes.ServeFiles(embedFS, "static"))
mux.Handle(
"POST /api/password",
middlewares.RateLimiter(
routes.CreatePassword(storage, 12*1024, base64.StdEncoding),
1*time.Minute,
5,
),
)
mux.Handle("GET /api/password/{id}", routes.GetPassword(storage, base64.StdEncoding))
mux.Handle("HEAD /api/password/{id}", routes.HasPassword(storage))
address := os.Getenv("PASSED_ADDRESS")
if address == "" {
log.Printf("No PASSED_ADDRESS provided, defaulting to \":3000\"")
address = ":3000"
}
log.Printf("Listening on %s", address)
err = http.ListenAndServe(address, middlewares.Logger(mux))
if err != nil {
return err
}
return nil
}
func main() {
err := run()
if err != nil {
log.Fatalf("%s", err)
}
}