added 500 response handler added info page handler
sophuwu sophie@sophuwu.site
Thu, 31 Aug 2023 23:19:11 +0100
1 files changed,
62 insertions(+),
4 deletions(-)
jump to
M
main.go
→
main.go
@@ -2,6 +2,7 @@ package main
import ( "encoding/json" + "errors" bolt "go.etcd.io/bbolt" "math/rand" "net/http"@@ -57,6 +58,9 @@ return word() + "-" + word() + "-" + word()
} func readURL(words string) (urlStruc, error) { + if words == "" { + return urlStruc{}, errors.New("No words provided") + } var url urlStruc var err error err = urlDB.View(func(tx *bolt.Tx) error {@@ -87,7 +91,7 @@ }
func http404(w http.ResponseWriter) { w.WriteHeader(404) - b, err := os.ReadFile("404.html") + b, err := os.ReadFile("html/404.html") if err != nil { b = []byte("404 not found") w.Header().Set("Content-Type", "text/plain")@@ -97,6 +101,53 @@ }
w.Write(b) } +func http500(w http.ResponseWriter) { + w.WriteHeader(500) + b, err := os.ReadFile("html/500.html") + if err != nil { + b = []byte("500 internal server error") + w.Header().Set("Content-Type", "text/plain") + } else { + w.Header().Set("Content-Type", "text/html") + } + w.Write(b) +} + +func intStr(n int) string { + if n == 0 { + return "0" + } + var s, sign string + if n < 0 { + sign = "-" + n = -n + } + for ; n > 0; n /= 10 { + s = string(n%10+int('0')) + s + } + return sign + s +} + +func infoPage(w http.ResponseWriter, url urlStruc) { + w.WriteHeader(200) + w.Header().Set("Content-Type", "text/html") + b, err := os.ReadFile("html/info.html") + if err != nil { + http500(w) + return + } + custom := "no" + if url.isCustom { + custom = "yes" + } + s := strings.ReplaceAll(string(b), "{{url}}", url.url) + s = strings.ReplaceAll(s, "{{path}}", url.path) + s = strings.ReplaceAll(s, "{{uses}}", intStr(url.uses)) + s = strings.ReplaceAll(s, "{{custom}}", custom) + s = strings.ReplaceAll(s, "{{date}}", url.date.Format("2006-01-02 15:04:05")) + w.Write([]byte(s)) +} + func httpHandler(w http.ResponseWriter, r *http.Request) { if len(r.URL.Path) > 1 { path := strings.TrimSuffix(r.URL.Path[1:], "/")@@ -106,12 +157,19 @@ info = true
path = strings.TrimSuffix(path, "/info") } url, err := readURL(path) - if url != "" { - http.Redirect(w, r, url, http.StatusFound) + if err != nil || url.url == "" { + http404(w) return } - http.Error(w, "404 not found", http.StatusNotFound) + if info { + infoPage(w, url) + return + } + http.Redirect(w, r, url.url, http.StatusFound) return + } + if r.Method == "POST" { + } }