-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
restapiItem.go
executable file
·72 lines (68 loc) · 1.72 KB
/
restapiItem.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
package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
func postHandleAPIItem(w http.ResponseWriter, r *http.Request) {
client, err := mongo.NewClient(options.Client().ApplyURI(*flagMongoDBURI))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer client.Disconnect(ctx)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// token 체크
_, _, err = TokenHandlerV2(r, client)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
i := Item{}
var unmarshalErr *json.UnmarshalTypeError
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
err = decoder.Decode(&i)
if err != nil {
if errors.As(err, &unmarshalErr) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
err = i.CheckError()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = addItemV2(client, i)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data, err := json.Marshal(i)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(data)
}