From 73c06c3636b2f634938cb6e4f50b109cdd4ae4b5 Mon Sep 17 00:00:00 2001 From: Ada Date: Tue, 3 Oct 2023 20:41:03 +0200 Subject: [PATCH] add(backend): inset data to db and check if path exist in db --- db.go | 2 +- main.go | 35 +++++++++++++++++++++++++++-------- utils.go | 23 ++++++++++++++++++++++- 3 files changed, 50 insertions(+), 10 deletions(-) diff --git a/db.go b/db.go index db17773..149fda1 100644 --- a/db.go +++ b/db.go @@ -18,7 +18,7 @@ func connectDB() *redis.Client { return db } -func insert_paste(key string, content string, secret string, ttl time.Duration) { +func insertPaste(key string, content string, secret string, ttl time.Duration) { type dbSchema struct { content string secret string diff --git a/main.go b/main.go index 627ed98..fb83c5e 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,8 @@ package main import ( + "fmt" + "io" "net/http" "strings" ) @@ -9,14 +11,31 @@ var currentConfig config func handleRequest(w http.ResponseWriter, r *http.Request) { path := r.URL.Path - if path == "/" { - http.ServeFile(w, r, "./static/index.html") + switch r.Method { + case "GET": + if path == "/" { + http.ServeFile(w, r, "./static/index.html") - } else if strings.HasPrefix(path, "/static/") { - fs := http.FileServer(http.Dir("./static")) - http.Handle("/static/", http.StripPrefix("/static/", fs)) - } else { - w.WriteHeader(http.StatusNotFound) + } else if strings.HasPrefix(path, "/static/") { + fs := http.FileServer(http.Dir("./static")) + http.Handle("/static/", http.StripPrefix("/static/", fs)) + } else { + if urlExist(path) { + io.WriteString(w, "exist") + } 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) + } } } @@ -28,6 +47,6 @@ func main() { err := http.ListenAndServe(listen, nil) if err != nil { - return + fmt.Println(err) } } diff --git a/utils.go b/utils.go index f94d64b..bef5176 100644 --- a/utils.go +++ b/utils.go @@ -1,6 +1,8 @@ package main -import "math/rand" +import ( + "math/rand" +) func generateUrl() string { length := currentConfig.urlLength @@ -12,3 +14,22 @@ func generateUrl() string { return string(b) } + +func generateSecret() string { + length := 32 + listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") + b := make([]rune, length) + for i := range b { + b[i] = listChars[rand.Intn(len(listChars))] + } + + return string(b) +} + +func urlExist(url string) bool { + exist := connectDB().Exists(ctx, url).Val() + if exist == 1 { + return true + } + return false +}