-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
43 lines (36 loc) · 1005 Bytes
/
api.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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
)
type PostData struct {
Key string
Target string
}
func DatabaseAPI(db ShortlinkDB) http.Handler {
router := http.NewServeMux()
router.HandleFunc("/manage/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusInternalServerError)
return
}
var data PostData
err = json.Unmarshal(body, &data)
if err != nil || data.Key == "" || data.Target == "" {
http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
return
}
if err = db.Add(data.Key, data.Target); err != nil {
http.Error(w, err.Error(), http.StatusPreconditionFailed)
} else {
w.WriteHeader(http.StatusCreated)
}
} else {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
}
})
return router
}