-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrollers.go
62 lines (50 loc) · 1.68 KB
/
controllers.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
package main
import (
"encoding/json"
"net/http"
"strings"
"github.com/xvargr/clippit/internal/URLShortener"
"github.com/xvargr/clippit/internal/config"
)
func HomepageHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/index.html")
}
func StaticHandler(w http.ResponseWriter, r *http.Request) {
fileName := r.PathValue("resourceName")
http.ServeFile(w, r, "./static/"+fileName)
}
func ShortenHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
originalURL := r.FormValue("url")
if originalURL == "" {
http.Error(w, "Incomplete form data, URL is required", http.StatusBadRequest)
return
}
if strings.Contains(originalURL, r.Host) {
http.Error(w, "Self referencing URLs are not allowed", http.StatusBadRequest)
return
}
shortenedURL := URLShortener.Instance().AddMapping(r, originalURL)
json.NewEncoder(w).Encode((map[string]string{"shortenedUrl": shortenedURL, "validity": config.GetConfig().PruneIntervalHour.String()}))
}
func ResolverHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
keyword := r.PathValue("keyword")
originalURL, ok := URLShortener.Instance().ResolveShortKeyToOriginal(keyword)
if !ok {
http.Error(w, "Not a valid short URL", http.StatusNotFound)
return
}
http.Redirect(w, r, originalURL, http.StatusSeeOther)
}
func HealthHandler(w http.ResponseWriter, r *http.Request) {
(w).Header().Set("Access-Control-Allow-Origin", "https://xvargr.dev")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}