plakken/main.go

100 lines
2.2 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"html/template"
"io"
"log"
"net/http"
"strings"
)
var currentConfig config
type pasteView struct {
Content string
Key string
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
2023-10-06 00:16:55 +02:00
path := r.URL.Path
clearPath := strings.ReplaceAll(r.URL.Path, "/raw", "")
db := connectDB()
switch r.Method {
case "GET":
if path == "/" {
http.ServeFile(w, r, "./static/index.html")
2023-10-06 00:16:55 +02:00
} else if strings.HasPrefix(path, "/static/") {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
} else {
2023-10-06 00:16:55 +02:00
if urlExist(clearPath) {
if strings.HasSuffix(path, "/raw") {
pasteContent := db.HGet(ctx, clearPath, "content").Val()
2023-10-12 21:46:30 +02:00
w.Header().Set("Content-Type", "text/plain")
_, err := io.WriteString(w, pasteContent)
2023-10-06 00:16:55 +02:00
if err != nil {
log.Println(err)
}
} else {
pasteContent := db.HGet(ctx, path, "content").Val()
s := pasteView{Content: pasteContent, Key: strings.TrimPrefix(path, "/")}
t, err := template.ParseFiles("templates/paste.html")
if err != nil {
log.Println(err)
}
err = t.Execute(w, s)
2023-10-06 00:16:55 +02:00
if err != nil {
log.Println(err)
}
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}
case "POST":
if path == "/" {
secret := generateSecret()
url := "/" + generateUrl()
content := r.FormValue("content")
insertPaste(url, content, secret, -1)
http.Redirect(w, r, url, http.StatusSeeOther)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
2023-10-12 21:46:30 +02:00
case "DELETE":
if urlExist(path) {
secret := r.URL.Query().Get("secret")
if secret == db.HGet(ctx, path, "secret").Val() {
err := db.Del(ctx, path)
if err != nil {
log.Println(err)
2023-10-12 21:46:30 +02:00
}
w.WriteHeader(http.StatusNoContent)
2023-10-12 21:46:30 +02:00
} else {
w.WriteHeader(http.StatusForbidden)
2023-10-12 21:46:30 +02:00
}
} else {
w.WriteHeader(http.StatusNotFound)
2023-10-12 21:46:30 +02:00
}
}
}
func main() {
currentConfig = getConfig()
2023-10-02 15:03:04 +02:00
listen := currentConfig.host + ":" + currentConfig.port
http.HandleFunc("/", handleRequest)
if currentConfig.host == "" {
fmt.Println("Listening on port " + listen)
} else {
fmt.Println("Listening on " + listen)
}
2023-10-02 15:03:04 +02:00
err := http.ListenAndServe(listen, nil)
if err != nil {
log.Fatal(err)
}
}