-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
81 lines (69 loc) · 2.03 KB
/
api.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
75
76
77
78
79
80
81
package actions
import (
"encoding/json"
"fmt"
"github.com/go-chi/chi"
"github.com/rubenwo/home-automation/services/actions-service/internal/actions/intentprocessor"
"github.com/rubenwo/home-automation/services/actions-service/internal/actions/models"
"log"
"net/http"
)
type api struct {
intentProcessors map[string]intentprocessor.IntentProcessor
}
func Run(cfg *Config) error {
if cfg == nil {
return ConfigNilError
}
if err := cfg.Validate(); err != nil {
return fmt.Errorf("%v: %w", ConfigValidationError, err)
}
a := &api{intentProcessors: cfg.IntentProcessors}
router := chi.NewRouter()
router.Get("/healthz", a.healthz)
router.Post("/webhook/request", a.onWebhookRequest)
if err := http.ListenAndServe(cfg.Addr, router); err != nil {
return err
}
return nil
}
func (a *api) healthz(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
if err := json.NewEncoder(w).Encode(&models.HealthzModel{
IsHealthy: true,
ErrorMessage: "",
}); err != nil {
log.Printf("error sending healthz: %s\n", err.Error())
}
}
func (a *api) onWebhookRequest(w http.ResponseWriter, r *http.Request) {
var req models.WebhookRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
log.Println(err)
return
}
fmt.Println(req)
fmt.Println(req.QueryResult.Intent.DisplayName)
processor, ok := a.intentProcessors[req.QueryResult.Intent.DisplayName]
if !ok {
w.WriteHeader(http.StatusBadRequest)
log.Println("processor for request not found")
return
}
msg, err := processor.ProcessIntent(req.QueryResult.Parameters)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
w.Header().Set("Content-Type", "application/json")
response := models.TextResponse{FulfillmentMessages: []models.Message{
models.Message{Text: models.Text{Text: []string{msg}}},
}}
if err := json.NewEncoder(w).Encode(&response); err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
}