-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler_public_index.go
More file actions
45 lines (40 loc) · 1 KB
/
handler_public_index.go
File metadata and controls
45 lines (40 loc) · 1 KB
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
package shortlinks
import (
"fmt"
"net/http"
"os"
"strings"
)
func publicIndexHandler(db PublicDB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
sl, err := db.AllShortlinks()
if err != nil {
fmt.Fprintln(os.Stderr, err)
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(500)
fmt.Fprintln(w, "couldn't load links")
return
}
v := index{Shortlinks: sl}
if err := tpl.ExecuteTemplate(w, "public_index.html", v); err != nil {
fmt.Fprintln(os.Stderr, err)
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(500)
fmt.Fprintln(w, "couldn't execute template")
return
}
return
}
sl, err := db.Shortlink(strings.TrimPrefix(r.URL.Path, "/"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(500)
fmt.Fprintln(w, "couldn't load link")
return
}
w.Header().Add("Location", sl.To)
w.WriteHeader(302)
})
}