Files
minibin/main.go
T

127 lines
2.9 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",
"templates/tos.html",
"templates/privacy.html",
"templates/faq.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()))
}
}
pastePlaceholders, err := os.ReadFile("paste-placeholders.txt")
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Fatal(err)
}
var placeholders []string
if err == nil {
content := strings.ReplaceAll(string(pastePlaceholders), "\r\n", "\n")
placeholders = strings.Split(strings.TrimSpace(content), "\n")
} else {
placeholders = []string{
"cmon, paste something already!",
}
}
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 {
data.Qt = qts[rand.IntN(len(qts))]
}
if len(placeholders) > 0 {
data.PastePlaceholder = placeholders[rand.IntN(len(placeholders))]
}
render(pages, w, "home.html", data)
})
mux.HandleFunc("GET /tos", staticPage(pages, "tos.html"))
mux.HandleFunc("GET /privacy", staticPage(pages, "privacy.html"))
mux.HandleFunc("GET /faq", func(w http.ResponseWriter, r *http.Request) {
render(pages, w, "faq.html", map[string]any{
"Expiries": config.Expiries,
"Host": config.Host,
})
})
mux.HandleFunc("GET /{id}", contentHandler(db, config))
mux.HandleFunc("POST /upload", uploadHandler(db, config, pages))
mux.HandleFunc("PUT /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)
}
}