Files
minibin/main.go
T
whoswhip 2c342f63b3 every file sharing service needs qts
honestly this code might be kind of shit, and it needs to used on the other page(s) as well but im too lazy, fixed a styling issue with the upload result page though
2026-11-12 22:30:36 -05:00

101 lines
2.1 KiB
Go

package main
import (
"errors"
"html/template"
"log"
"math/rand/v2"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
)
func main() {
config, err := loadConfig()
if err != nil {
log.Fatal(err)
}
log.Println("config loaded")
db, err := initDatabase(config.DatabasePath)
if err != nil {
log.Fatal(err)
}
log.Println("database initialized")
if err := os.MkdirAll(config.UploadDir, 0700); err != nil {
log.Fatal(err)
}
pages, err := template.New("").Funcs(template.FuncMap{
"hasPrefix": strings.HasPrefix,
}).ParseFiles(
"templates/home.html",
"templates/header.html",
"templates/upload.html",
)
if err != nil {
log.Fatal(err)
}
qtFiles, err := os.ReadDir("qts")
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Fatal(err)
}
var qts []string
for _, qt := range qtFiles {
if qt.IsDir() {
continue
}
switch strings.ToLower(filepath.Ext(qt.Name())) {
case ".jpeg", "jpg", ".jxl", ".png", ".webp", "avif", ".gif":
qts = append(qts, "/qts/"+url.PathEscape(qt.Name()))
}
}
mux := http.NewServeMux()
fs := http.FileServer(http.Dir("static"))
mux.Handle("GET /css/", fs)
mux.Handle("GET /js/", fs)
mux.Handle("GET /static/", http.StripPrefix("/static/", fs))
mux.Handle("GET /qts/", http.StripPrefix(
"/qts/",
http.FileServer((http.Dir("qts"))),
))
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
data := HomePageData{
Expiries: config.Expiries,
}
if len(qts) > 0 {
log.Println(len(qts))
data.Qt = qts[rand.IntN(len(qts))]
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := pages.ExecuteTemplate(w, "home.html", data); err != nil {
log.Println("render home page:", err)
}
})
mux.HandleFunc("GET /{id}", contentHandler(db, config))
mux.HandleFunc("POST /upload", uploadHandler(db, config, pages))
mux.HandleFunc("DELETE /{id}", deleteHandler(db, config))
mux.HandleFunc("POST /{id}/delete", deleteHandler(db, config))
mux.HandleFunc("GET /health", health)
log.Println("listening on http://localhost:8080")
err = http.ListenAndServe("localhost:8080", mux)
if err != nil {
log.Fatal(err)
}
}