-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
66 lines (52 loc) · 1.28 KB
/
server.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
package main
import (
"fmt"
"io"
"net/http"
"strings"
)
type SixelServer struct {
store SixelStore
http.Handler
}
type SixelStore interface {
GetSixelImage(id string) string
StoreSixelImage(id, image string)
}
func NewSixelServer(store SixelStore) *SixelServer {
s := new(SixelServer)
s.store = store
router := http.NewServeMux()
router.Handle("/image/", http.HandlerFunc(s.getImageHandler))
router.Handle("/upload/", http.HandlerFunc(s.postImageHandler))
s.Handler = router
return s
}
func (s *SixelServer) getImageHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusBadRequest)
return
}
id := strings.TrimPrefix(r.URL.Path, "/image/")
image := s.store.GetSixelImage(id)
if image == "" {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Requested image not found.")
return
}
fmt.Fprint(w, image)
}
func (s *SixelServer) postImageHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusBadRequest)
return
}
id := strings.TrimPrefix(r.URL.Path, "/upload/")
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
s.store.StoreSixelImage(id, string(body))
}