-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathapi_link.go
74 lines (67 loc) · 1.78 KB
/
api_link.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
package shortpaste
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"text/template"
)
func (app *App) handleLink(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
app.handleGetLink(w, r)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func (app *App) handleGetLinks(w http.ResponseWriter, r *http.Request) {
var links []Link
app.db.Find(&links)
json.NewEncoder(w).Encode(map[string][]Link{"links": links})
}
func (app *App) handleGetLink(w http.ResponseWriter, r *http.Request) {
id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/l/"), "/")
if id == "" {
onNotFound(w, "No ID found in request")
return
}
var link Link
if err := app.db.First(&link, "id = ?", id).Error; err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Link for `%s` not found!\n", id)
return
}
if app.link307Redirect {
http.Redirect(w, r, link.Link, http.StatusTemporaryRedirect)
} else {
t, err := template.ParseFS(templateFS, "templates/link.html")
if err != nil {
onServerError(w, err, "failed to parse template")
return
}
t.Execute(w, link)
}
link.HitCount += 1
app.db.Save(&link)
}
func (app *App) handleCreateLink(w http.ResponseWriter, r *http.Request) {
link := Link{}
if err := json.NewDecoder(r.Body).Decode(&link); err != nil {
onClientError(w, err, "check the input and try again")
return
}
id := strings.TrimPrefix(r.URL.Path, "/l/")
if id != "" && link.ID == "" {
link.ID = id
}
if err := link.validate(); err != nil {
onClientError(w, err, "check the input and try again")
return
}
if err := app.db.Create(&link).Error; err != nil {
onServerError(w, err, "failed to create DB entry")
return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]string{"message": "created"})
}