-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
65 lines (54 loc) · 1.53 KB
/
handlers.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
// Package api provides the web interface
package api
import (
"context"
"log"
"net/http"
"os"
"time"
pb "github.com/foroozf001/broker-service/internal/proto/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// JSONPayload is the type for json posted to this api
type JSONPayload struct {
Name string `json:"name"`
Data string `json:"data"`
}
// LogViaGRPC takes a JSON payload and logs it via gRPC
func (app *Config) LogViaGRPC(w http.ResponseWriter, r *http.Request) {
var requestPayload JSONPayload
err := app.readJSON(w, r, &requestPayload)
if err != nil {
_ = app.errorJSON(w, r, err, http.StatusBadRequest)
return
}
loggerServiceURI, exists := os.LookupEnv("LOGGER_SERVICE_URI")
if !exists {
log.Println("missing logger service uri")
return
}
connection, err := grpc.Dial(loggerServiceURI, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
if err != nil {
_ = app.errorJSON(w, r, err, http.StatusInternalServerError)
return
}
defer connection.Close()
c := pb.NewLogServiceClient(connection)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_, err = c.WriteLog(ctx, &pb.LogRequest{
LogEntry: &pb.Log{
Name: requestPayload.Name,
Data: requestPayload.Data,
},
})
if err != nil {
_ = app.errorJSON(w, r, err, http.StatusInternalServerError)
return
}
var payload jsonResponse
payload.Error = false
payload.Message = "logged event " + requestPayload.Name
_ = app.writeJSON(w, r, http.StatusAccepted, payload)
}