-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
95 lines (77 loc) · 1.88 KB
/
Copy pathserver.go
File metadata and controls
95 lines (77 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
92
93
94
95
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/google/uuid"
)
type server struct {
router *chi.Mux
entries map[string]textData
}
func healthCheck(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%s", `{"status":"OK"}`)
}
func sendText(s *server) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var newText textData
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, err.Error())
}
json.Unmarshal(reqBody, &newText)
var id string
for {
id = uuid.New().String()
if _, ok := s.entries[id]; !ok {
break
}
}
s.entries[id] = newText
w.WriteHeader(http.StatusCreated)
Conv, _ := json.Marshal(textID{ID: id})
fmt.Fprintf(w, "%s", string(Conv))
}
}
func pasteText(s *server) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
id := chi.URLParam(r, "id")
text, ok := s.entries[id]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
newEntry := textEntry{
textID{
id,
},
textData{
Description: text.Description,
Content: text.Content,
},
}
conv, _ := json.Marshal(newEntry)
fmt.Fprintf(w, "%s", string(conv))
}
}
func newServer() *server {
var s server
s.entries = make(map[string]textData)
s.router = chi.NewRouter()
s.router.Use(middleware.Logger)
s.router.Get("/healthy", healthCheck)
s.router.Post("/", sendText(&s))
s.router.Get("/paste/{id}", pasteText(&s))
return &s
}
func (s *server) Run(addr string) error {
return http.ListenAndServe(addr, s.router)
}