-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
91 lines (76 loc) · 1.88 KB
/
server.go
File metadata and controls
91 lines (76 loc) · 1.88 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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"embed"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"github.com/gorilla/mux"
)
//go:embed templates/*.html
var templatesContent embed.FS
type Server struct {
Port string
StorageClient *StorageClient
}
type Link struct {
IsVideo bool
IsImage bool
Url string
}
func (s Server) Start() {
r := mux.NewRouter()
r.HandleFunc("/", s.Index).Methods("GET")
r.HandleFunc("/delete", s.Delete).Methods("POST")
addr := fmt.Sprintf(":%s", s.Port)
log.Printf("Listening %s", addr)
log.Fatal(http.ListenAndServe(addr, r))
}
func (s Server) Index(w http.ResponseWriter, r *http.Request) {
keys, err := s.StorageClient.ListObjects(r2BucketName, "shots")
if err != nil {
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500)
return
}
renderTemplate(w, "index.html", struct {
Links []Link
}{
Links: createLinks(keys),
})
}
func (s Server) Delete(w http.ResponseWriter, r *http.Request) {
url := r.FormValue("url")
if strings.TrimSpace(url) == "" {
http.Error(w, "invalid url", 400)
return
}
key := strings.TrimPrefix(strings.TrimPrefix(url, r2BucketDomain), "/")
if err := s.StorageClient.DeleteObject(r2BucketName, key); err != nil {
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500)
return
}
}
func renderTemplate(w http.ResponseWriter, name string, data interface{}) {
t, err := template.ParseFS(templatesContent, "templates/*.html")
if err != nil {
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500)
return
}
err = t.ExecuteTemplate(w, name, data)
if err != nil {
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500)
return
}
}
func createLinks(keys []string) []Link {
links := []Link{}
for _, key := range keys {
links = append(links, Link{
IsVideo: strings.HasSuffix(key, "mp4"),
IsImage: strings.HasSuffix(key, "png"),
Url: fmt.Sprintf("%s/%s", r2BucketDomain, key),
})
}
return links
}