add(backend): inset data to db and check if path exist in db

This commit is contained in:
Ada 2023-10-03 20:41:03 +02:00
parent 85dff8deca
commit 73c06c3636
3 changed files with 50 additions and 10 deletions

2
db.go
View file

@ -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

21
main.go
View file

@ -1,6 +1,8 @@
package main
import (
"fmt"
"io"
"net/http"
"strings"
)
@ -9,15 +11,32 @@ var currentConfig config
func handleRequest(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
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 {
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)
}
}

View file

@ -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
}