forked from agtorre/go-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get.go
38 lines (32 loc) · 854 Bytes
/
get.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
package main
import (
"encoding/json"
"net/http"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue"
"github.com/apex/log"
)
// GetHandler wraps our RPC Get call
func (c *Controller) GetHandler(w http.ResponseWriter, r *http.Request) {
key := r.URL.Query().Get("key")
kv := keyvalue.GetKeyValueRequest{Key: key}
gresp, err := c.Get(r.Context(), &kv)
if err != nil {
if grpc.Code(err) == codes.NotFound {
w.WriteHeader(http.StatusNotFound)
return
}
log.Errorf("failed to get: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
resp, err := json.Marshal(gresp)
if err != nil {
log.Errorf("failed to marshal: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(resp)
}