Merge pull request 'Paste view' (#2) from view-paste into main

Reviewed-on: #2
This commit is contained in:
Ada 2023-10-10 17:10:15 +00:00
commit 743c83272f
2 changed files with 43 additions and 5 deletions

33
main.go
View file

@ -2,6 +2,7 @@ package main
import ( import (
"fmt" "fmt"
"html/template"
"io" "io"
"log" "log"
"net/http" "net/http"
@ -10,20 +11,42 @@ import (
var currentConfig config var currentConfig config
type pasteView struct {
Content string
Key string
}
func handleRequest(w http.ResponseWriter, r *http.Request) { func handleRequest(w http.ResponseWriter, r *http.Request) {
path := strings.ReplaceAll(r.URL.Path, "/raw", "") path := r.URL.Path
clearPath := strings.ReplaceAll(r.URL.Path, "/raw", "")
db := connectDB()
switch r.Method { switch r.Method {
case "GET": case "GET":
if path == "/" { if path == "/" {
http.ServeFile(w, r, "./static/index.html") http.ServeFile(w, r, "./static/index.html")
} else if strings.HasPrefix(path, "/static/") { } else if strings.HasPrefix(path, "/static/") {
fs := http.FileServer(http.Dir("./static")) fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs)) http.Handle("/static/", http.StripPrefix("/static/", fs))
} else { } else {
if urlExist(path) { if urlExist(clearPath) {
_, err := io.WriteString(w, "This plak exists") if strings.HasSuffix(path, "/raw") {
if err != nil { pasteContent := db.HGet(ctx, clearPath, "content").Val()
return _, err := io.WriteString(w, pasteContent)
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)
if err != nil {
log.Println(err)
}
} }
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)

15
templates/paste.html Normal file
View file

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{.Key}}</title>
<meta charset="UTF-8">
<meta content="width=device-width, user-scalable=no, initial-scale=1.0"
name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<title>Plak {{.Key}}• Plakken</title>
<link href="/static/style.css" rel="stylesheet">
</head>
<body>
<pre><code>{{.Content}}</code></pre>
</body>
</html>