/
handler.go
41 lines (37 loc) · 904 Bytes
/
handler.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
package api
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strings"
)
// CRUDHandler .
type CRUDHandler interface {
Create(w http.ResponseWriter, r *http.Request)
Read(w http.ResponseWriter, r *http.Request)
Update(w http.ResponseWriter, r *http.Request)
Delete(w http.ResponseWriter, r *http.Request)
}
func parseBody(r *http.Request) (map[string]interface{}, error) {
if r.Method != http.MethodPost {
return nil, errors.New("http method is not POST")
}
var body map[string]interface{}
raw, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
if err := json.Unmarshal(raw, &body); err != nil {
return nil, err
}
return body, nil
}
func parseIdentifier(r *http.Request, endpoint string) string {
split := strings.Split(r.URL.Path, "/")
lastIdx := len(split) - 1
if strings.Contains(endpoint, split[lastIdx]) {
return ""
}
return split[lastIdx]
}