-
Notifications
You must be signed in to change notification settings - Fork 0
/
getData.go
59 lines (51 loc) · 1.27 KB
/
getData.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
package networkutil
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
)
func GetHeader(w http.ResponseWriter, req *http.Request) (map[string]string, error) {
if req.Method != "POST" {
ErrorStatus(w)
return nil, fmt.Errorf("bad request")
}
if req.Header.Get("Content-Type") != "application/json" {
ErrorStatus(w)
return nil, fmt.Errorf("bad request")
}
length, err := strconv.Atoi(req.Header.Get("Content-Length"))
if err != nil {
ErrorStatus(w)
return nil, fmt.Errorf("content-length flags is not found")
}
body := make([]byte, length)
length, err = req.Body.Read(body)
if err != nil && err != io.EOF {
ErrorStatus(w)
return nil, fmt.Errorf("parse error")
}
var jsonBody map[string]string
err = json.Unmarshal(body[:length], &jsonBody)
if err != nil {
ErrorStatus(w)
fmt.Println(err)
return nil, fmt.Errorf("parse error")
}
return jsonBody, nil
}
func PickValue(key string, data map[string]string, w http.ResponseWriter) (string, error) {
if value, ok := data[key]; ok {
return value, nil
}
ErrorStatus(w)
return "", fmt.Errorf("Key is not found")
}
func GetFromKey(key string, w http.ResponseWriter, req *http.Request) (string, error) {
body, err := GetHeader(w, req)
if err != nil {
return "", err
}
return PickValue(key, body, w)
}