From a3d7b2b9da75b324aa0d88e46774bc729cecf166 Mon Sep 17 00:00:00 2001 From: Ada Date: Mon, 2 Oct 2023 20:33:13 +0200 Subject: [PATCH] begin work for handle POST form --- db.go | 36 ++++++++++++++++++++++++++++++++++++ main.go | 22 ++++++++++++++-------- utils.go | 14 ++++++++++++++ 3 files changed, 64 insertions(+), 8 deletions(-) create mode 100644 db.go create mode 100644 utils.go diff --git a/db.go b/db.go new file mode 100644 index 0000000..db17773 --- /dev/null +++ b/db.go @@ -0,0 +1,36 @@ +package main + +import ( + "context" + "github.com/redis/go-redis/v9" + "time" +) + +var ctx = context.Background() + +func connectDB() *redis.Client { + db := redis.NewClient(&redis.Options{ + Addr: currentConfig.redisAddr, + Username: currentConfig.redisUser, + Password: currentConfig.redisPassword, + DB: currentConfig.redisDB, + }) + return db +} + +func insert_paste(key string, content string, secret string, ttl time.Duration) { + type dbSchema struct { + content string + secret string + } + + hash := dbSchema{ + content: content, + secret: secret, + } + connectDB().HSet(ctx, key, "content", hash.content) + connectDB().HSet(ctx, key, "secret", hash.secret) + if ttl > -1 { + connectDB().Do(ctx, key, ttl) + } +} diff --git a/main.go b/main.go index 627ed98..37003ef 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "net/http" "strings" ) @@ -9,14 +10,19 @@ 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 { + w.WriteHeader(http.StatusNotFound) + } + case "POST": + fmt.Println("Post!") } } @@ -28,6 +34,6 @@ func main() { err := http.ListenAndServe(listen, nil) if err != nil { - return + fmt.Println(err) } } diff --git a/utils.go b/utils.go new file mode 100644 index 0000000..f94d64b --- /dev/null +++ b/utils.go @@ -0,0 +1,14 @@ +package main + +import "math/rand" + +func generateUrl() string { + length := currentConfig.urlLength + listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") + b := make([]rune, length) + for i := range b { + b[i] = listChars[rand.Intn(len(listChars))] + } + + return string(b) +}