forked from agtorre/go-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
43 lines (36 loc) · 995 Bytes
/
set.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"
"net/http"
"github.com/agtorre/go-cookbook/chapter7/grpcjson/internal"
"github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue"
"github.com/apex/log"
)
// Controller holds an internal KeyValueObject
type Controller struct {
*internal.KeyValue
}
// SetHandler wraps or GRPC Set
func (c *Controller) SetHandler(w http.ResponseWriter, r *http.Request) {
var kv keyvalue.SetKeyValueRequest
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&kv); err != nil {
log.Errorf("failed to decode: %s", err.Error())
w.WriteHeader(http.StatusBadRequest)
return
}
gresp, err := c.Set(r.Context(), &kv)
if err != nil {
log.Errorf("failed to set: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
resp, err := json.Marshal(gresp)
if err != nil {
log.Errorf("failed to marshal: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(resp)
}