organize
This commit is contained in:
+2
-65
@@ -8,7 +8,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
@@ -20,18 +19,9 @@ import (
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/gabriel-vasile/mimetype"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type HomePageData struct {
|
||||
Expiries []Expiry
|
||||
Qt string
|
||||
PastePlaceholder string
|
||||
FileMaxSize string
|
||||
PasteMaxSize string
|
||||
}
|
||||
|
||||
func health(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
fmt.Fprintln(w, "OK")
|
||||
@@ -56,20 +46,7 @@ type ContentInfoResponse struct {
|
||||
Filename string `json:"-"`
|
||||
}
|
||||
|
||||
func render(pages *template.Template, w http.ResponseWriter, name string, data any) {
|
||||
w.Header().Set("Conten-Type", "text/html; charset=utf-8")
|
||||
if err := pages.ExecuteTemplate(w, name, data); err != nil {
|
||||
log.Printf("render %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func staticPage(pages *template.Template, name string, qts []string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
render(pages, w, name, getRandomQt(qts))
|
||||
}
|
||||
}
|
||||
|
||||
func uploadHandler(db *gorm.DB, cfg Config, pages *template.Template, qts []string) http.HandlerFunc {
|
||||
func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost && r.Method != http.MethodPut {
|
||||
w.Header().Set("Allow", "POST,PUT")
|
||||
@@ -281,7 +258,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *template.Template, qts []stri
|
||||
SHA256: hex.EncodeToString(upload.SHA256),
|
||||
DeleteToken: upload.DeleteToken,
|
||||
FileExtension: filepath.Ext(upload.Filename),
|
||||
Qt: getRandomQt(qts),
|
||||
Qt: getRandomQt(pages.Qts),
|
||||
}
|
||||
|
||||
switch returnType {
|
||||
@@ -466,43 +443,3 @@ func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func detectMimeType(file io.ReadSeeker) (string, error) {
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return "", fmt.Errorf("rewind file: %w", err)
|
||||
}
|
||||
|
||||
mtype, dtcErr := mimetype.DetectReader(file)
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return "", fmt.Errorf("rewind file: %w", err)
|
||||
}
|
||||
|
||||
if dtcErr != nil {
|
||||
return "", fmt.Errorf("detect MIME type: %w", dtcErr)
|
||||
}
|
||||
|
||||
return mtype.String(), nil
|
||||
}
|
||||
|
||||
func normalizeMIMEType(contentType string) string {
|
||||
const plaintext = "text/plain; charset=utf-8"
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return plaintext
|
||||
}
|
||||
if strings.HasSuffix(mediaType, "+xml") {
|
||||
return plaintext
|
||||
}
|
||||
switch mediaType {
|
||||
case "text/html", "text/javascript", "application/javascript",
|
||||
"application/ecmascript", "text/ecmascript", "application/xml",
|
||||
"text/xml", "text/xsl",
|
||||
"text/css", "application/wasm":
|
||||
return plaintext
|
||||
case "application/pdf":
|
||||
return "application/octet-stream"
|
||||
default:
|
||||
return contentType
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,9 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"html/template"
|
||||
"log"
|
||||
"math/rand/v2"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -35,45 +27,11 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
pages, err := template.New("").Funcs(template.FuncMap{
|
||||
"hasPrefix": strings.HasPrefix,
|
||||
}).ParseGlob("templates/*.html")
|
||||
pages, err := loadPages()
|
||||
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!",
|
||||
}
|
||||
}
|
||||
|
||||
tracker := &AccessTracker{
|
||||
pending: make(map[string]int64),
|
||||
}
|
||||
@@ -81,60 +39,10 @@ func main() {
|
||||
defer cancel()
|
||||
go tracker.Run(ctx, db)
|
||||
|
||||
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,
|
||||
FileMaxSize: humanize.Bytes(uint64(config.MaxFileBytes)),
|
||||
PasteMaxSize: humanize.Bytes(uint64(config.MaxPasteBytes)),
|
||||
Qt: getRandomQt(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", qts))
|
||||
mux.HandleFunc("GET /privacy", staticPage(pages, "privacy.html", qts))
|
||||
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,
|
||||
"NormalizeMIMETypes": config.NormalizeMIMETypes,
|
||||
"Qt": getRandomQt(qts),
|
||||
})
|
||||
})
|
||||
uploads := http.NewServeMux()
|
||||
uploads.HandleFunc("GET /{id}", contentHandler(db, config, tracker))
|
||||
uploads.HandleFunc("GET /{id}/info", contentInfoHandler(db, tracker))
|
||||
mux.Handle("/", uploads)
|
||||
mux.HandleFunc("POST /upload", uploadHandler(db, config, pages, qts))
|
||||
mux.HandleFunc("PUT /upload", uploadHandler(db, config, pages, qts))
|
||||
mux.HandleFunc("DELETE /{id}", deleteHandler(db, config))
|
||||
mux.HandleFunc("POST /{id}/delete", deleteHandler(db, config))
|
||||
mux.HandleFunc("GET /health", health)
|
||||
|
||||
log.Println("listening on", config.Addr)
|
||||
|
||||
err = http.ListenAndServe(config.Addr, mux)
|
||||
router := newRouter(db, config, pages, tracker)
|
||||
err = http.ListenAndServe(config.Addr, router)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func getRandomQt(qts []string) string {
|
||||
if len(qts) > 0 {
|
||||
return qts[rand.IntN(len(qts))]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"strings"
|
||||
|
||||
"github.com/gabriel-vasile/mimetype"
|
||||
)
|
||||
|
||||
func detectMimeType(file io.ReadSeeker) (string, error) {
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return "", fmt.Errorf("rewind file: %w", err)
|
||||
}
|
||||
|
||||
mtype, dtcErr := mimetype.DetectReader(file)
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return "", fmt.Errorf("rewind file: %w", err)
|
||||
}
|
||||
|
||||
if dtcErr != nil {
|
||||
return "", fmt.Errorf("detect MIME type: %w", dtcErr)
|
||||
}
|
||||
|
||||
return mtype.String(), nil
|
||||
}
|
||||
|
||||
func normalizeMIMEType(contentType string) string {
|
||||
const plaintext = "text/plain; charset=utf-8"
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return plaintext
|
||||
}
|
||||
if strings.HasSuffix(mediaType, "+xml") {
|
||||
return plaintext
|
||||
}
|
||||
switch mediaType {
|
||||
case "text/html", "text/javascript", "application/javascript",
|
||||
"application/ecmascript", "text/ecmascript", "application/xml",
|
||||
"text/xml", "text/xsl",
|
||||
"text/css", "application/wasm":
|
||||
return plaintext
|
||||
case "application/pdf":
|
||||
return "application/octet-stream"
|
||||
default:
|
||||
return contentType
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"html/template"
|
||||
"log"
|
||||
"math/rand/v2"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
)
|
||||
|
||||
type Pages struct {
|
||||
Templates *template.Template
|
||||
Qts []string
|
||||
Placeholders []string
|
||||
}
|
||||
|
||||
type HomePageData struct {
|
||||
Expiries []Expiry
|
||||
Qt string
|
||||
PastePlaceholder string
|
||||
FileMaxSize string
|
||||
PasteMaxSize string
|
||||
}
|
||||
|
||||
func render(pages *Pages, w http.ResponseWriter, name string, data any) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := pages.Templates.ExecuteTemplate(w, name, data); err != nil {
|
||||
log.Printf("render %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func staticPage(pages *Pages, name string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
render(pages, w, name, getRandomQt(pages.Qts))
|
||||
}
|
||||
}
|
||||
|
||||
func getRandomQt(qts []string) string {
|
||||
if len(qts) > 0 {
|
||||
return qts[rand.IntN(len(qts))]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func loadPages() (*Pages, error) {
|
||||
templates, err := template.New("").Funcs(template.FuncMap{
|
||||
"hasPrefix": strings.HasPrefix,
|
||||
}).ParseGlob("templates/*.html")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pages := &Pages{
|
||||
Templates: templates,
|
||||
Placeholders: []string{"cmon, paste something already!"},
|
||||
}
|
||||
|
||||
qtFiles, err := os.ReadDir("qts")
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
for _, qt := range qtFiles {
|
||||
if qt.IsDir() {
|
||||
continue
|
||||
}
|
||||
|
||||
switch strings.ToLower(filepath.Ext(qt.Name())) {
|
||||
case ".jpeg", ".jpg", ".jxl", ".png", ".webp", ".avif", ".gif":
|
||||
pages.Qts = append(pages.Qts, "/qts/"+url.PathEscape(qt.Name()))
|
||||
}
|
||||
}
|
||||
|
||||
pastePlaceholders, err := os.ReadFile("paste-placeholders.txt")
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
placeholders := strings.TrimSpace(strings.ReplaceAll(string(pastePlaceholders), "\r\n", "\n"))
|
||||
if placeholders != "" {
|
||||
pages.Placeholders = strings.Split(placeholders, "\n")
|
||||
}
|
||||
return pages, nil
|
||||
}
|
||||
|
||||
func homeHandler(pages *Pages, cfg Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
data := HomePageData{
|
||||
Expiries: cfg.Expiries,
|
||||
FileMaxSize: humanize.Bytes(uint64(cfg.MaxFileBytes)),
|
||||
PasteMaxSize: humanize.Bytes(uint64(cfg.MaxPasteBytes)),
|
||||
Qt: getRandomQt(pages.Qts),
|
||||
}
|
||||
|
||||
if len(pages.Placeholders) > 0 {
|
||||
data.PastePlaceholder = pages.Placeholders[rand.IntN(len(pages.Placeholders))]
|
||||
}
|
||||
|
||||
render(pages, w, "home.html", data)
|
||||
}
|
||||
}
|
||||
|
||||
func faqHandler(pages *Pages, cfg Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
render(pages, w, "faq.html", map[string]any{
|
||||
"Expiries": cfg.Expiries,
|
||||
"Host": cfg.Host,
|
||||
"NormalizeMIMETypes": cfg.NormalizeMIMETypes,
|
||||
"Qt": getRandomQt(pages.Qts),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newRouter(db *gorm.DB, cfg Config, pages *Pages, tracker *AccessTracker) http.Handler {
|
||||
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 /{$}", homeHandler(pages, cfg))
|
||||
mux.HandleFunc("GET /tos", staticPage(pages, "tos.html"))
|
||||
mux.HandleFunc("GET /privacy", staticPage(pages, "privacy.html"))
|
||||
mux.HandleFunc("GET /faq", faqHandler(pages, cfg))
|
||||
uploads := http.NewServeMux()
|
||||
uploads.HandleFunc("GET /{id}", contentHandler(db, cfg, tracker))
|
||||
uploads.HandleFunc("GET /{id}/info", contentInfoHandler(db, tracker))
|
||||
mux.Handle("/", uploads)
|
||||
mux.HandleFunc("POST /upload", uploadHandler(db, cfg, pages))
|
||||
mux.HandleFunc("PUT /upload", uploadHandler(db, cfg, pages))
|
||||
mux.HandleFunc("DELETE /{id}", deleteHandler(db, cfg))
|
||||
mux.HandleFunc("POST /{id}/delete", deleteHandler(db, cfg))
|
||||
mux.HandleFunc("GET /health", health)
|
||||
return mux
|
||||
}
|
||||
Reference in New Issue
Block a user