-
Notifications
You must be signed in to change notification settings - Fork 6
/
function.go
74 lines (60 loc) · 1.47 KB
/
function.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
67
68
69
70
71
72
73
74
package taskmanager
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
)
// TaskManager is entry point of Cloud Functions.
func TaskManager(w http.ResponseWriter, r *http.Request) {
switch r.Method {
// 新規作成
case http.MethodPost:
param, code, err := getJSON(r.Header.Get("Content-Type"), r.Body)
if err != nil {
responseWrite(w, code, err.Error(), err)
return
}
t := newTask(param.Title)
if err := t.add(); err != nil {
responseWrite(w, http.StatusInternalServerError, err.Error(), err)
return
}
msg := fmt.Sprintf("%v added", t.Title)
responseWrite(w, http.StatusOK, msg, nil)
// 一覧取得
case http.MethodGet:
// ステータス変更
case http.MethodPatch:
// 削除
case http.MethodDelete:
default:
e := errors.New("method not allowed")
responseWrite(w, http.StatusMethodNotAllowed, e.Error(), e)
}
return
}
func responseWrite(w http.ResponseWriter, code int, msg string, err error) {
if err != nil {
log.Println(err)
}
w.WriteHeader(code)
w.Write([]byte(msg))
}
func getJSON(contentType string, body io.Reader) (Parameter, int, error) {
var p Parameter
if contentType != "application/json" {
return p, http.StatusBadRequest, errors.New("invalid Content Type")
}
b, err := ioutil.ReadAll(body)
if err != nil {
return p, http.StatusInternalServerError, err
}
if err = json.Unmarshal(b, &p); err != nil {
return p, http.StatusInternalServerError, err
}
return p, http.StatusOK, nil
}