-
Notifications
You must be signed in to change notification settings - Fork 0
/
urlsHandler.go
76 lines (67 loc) · 2.1 KB
/
urlsHandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package handlers
import (
"errors"
"github.com/rzaf/url-shortener-api/helpers"
"github.com/rzaf/url-shortener-api/models"
"net/http"
"os"
"github.com/go-chi/chi"
)
func GetUrls(w http.ResponseWriter, r *http.Request) {
var user *models.User = r.Context().Value(models.User{}).(*models.User)
urls := models.GetUserUrls(int(user.Id))
if len(urls) == 0 {
w.WriteHeader(http.StatusNoContent)
return
}
helpers.WriteJson(w, urls, 200)
}
func DeleteUrl(w http.ResponseWriter, r *http.Request) {
var user *models.User = r.Context().Value(models.User{}).(*models.User)
short := chi.URLParam(r, "short")
url := models.GetUrl(short)
if !user.IsAdmin && url.User_id != user.Id {
helpers.WriteJsonError(w, errors.New("user not authorized"), 403)
return
}
models.DeleteUrl(short)
helpers.WriteJson(w, map[string]string{
"message": "url `" + short + "` deleted",
}, 200)
}
func GetUrl(w http.ResponseWriter, r *http.Request) {
short := chi.URLParam(r, "short")
url := models.GetUrl(short)
helpers.WriteJson(w, url, 200)
}
func CreateUrl(w http.ResponseWriter, r *http.Request) {
var user *models.User = r.Context().Value(models.User{}).(*models.User)
var body map[string]string
helpers.ReadJson(r, &body)
urlStr := body["url"]
helpers.ValidateVar(urlStr, "Url", "required,url")
urlId := models.CreateUrl(urlStr, user.Id)
helpers.WriteJson(w, map[string]any{
"message": "url created",
"shortened": models.IdToShort(int(urlId)),
"shortened_url": os.Getenv("URL") + "/" + models.IdToShort(int(urlId)),
}, 201)
}
func EditUrl(w http.ResponseWriter, r *http.Request) {
var user *models.User = r.Context().Value(models.User{}).(*models.User)
short := chi.URLParam(r, "short")
var body map[string]string
helpers.ReadJson(r, &body)
newUrlStr := body["url"]
helpers.ValidateVar(newUrlStr, "Url", "required,url")
url := models.GetUrl(short)
if !user.IsAdmin && url.User_id != user.Id {
helpers.WriteJsonError(w, errors.New("user not authorized"), 403)
return
}
models.EditUrl(short, newUrlStr)
helpers.WriteJson(w, map[string]any{
"message": "url edited",
"url": newUrlStr,
}, 200)
}