-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
74 lines (66 loc) · 2.1 KB
/
handler.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
package alexa
import (
"encoding/json"
"io/ioutil"
"math"
"net/http"
"time"
"go.uber.org/zap"
)
type Handler struct {
Skill Skill
Log *zap.SugaredLogger
ExpectedApplicationID string
SkipRequestValidation bool
}
type Skill interface {
ProcessRequest(requestEnv *RequestEnvelope) *ResponseEnvelope
}
func (h *Handler) Handle(w http.ResponseWriter, req *http.Request) {
const timeLimit float64 = 150
if !h.SkipRequestValidation && !IsValidAlexaRequest(w, req) {
return
}
requestBody, e := ioutil.ReadAll(req.Body)
if e != nil {
h.Log.Errorw("Error while reading request body", "error", e)
w.WriteHeader(http.StatusInternalServerError)
return
}
var alexaRequest RequestEnvelope
e = json.Unmarshal(requestBody, &alexaRequest)
if e != nil {
h.Log.Errorw("Error while unmarshaling request body", "error", e)
w.WriteHeader(http.StatusBadRequest)
return
}
if alexaRequest.Session == nil {
h.Log.Infow("Session is empty", "error", e)
http.Error(w, "Session is empty", http.StatusBadRequest)
return
}
if alexaRequest.Session.Application.ApplicationID != h.ExpectedApplicationID {
h.Log.Infof("ApplicationID does not match: %v", alexaRequest.Session.Application.ApplicationID)
http.Error(w, "Invalid ApplicationID", http.StatusBadRequest)
return
}
timestamp, e := time.Parse("2006-01-02T15:04:05Z", alexaRequest.Request.Timestamp)
if e != nil {
h.Log.Infof("Invalid timestamp. Timestamp: %v", alexaRequest.Request.Timestamp)
http.Error(w, "Invalid Timestamp", http.StatusBadRequest)
return
}
if math.Abs(time.Since(timestamp).Seconds()) > timeLimit {
h.Log.Infow("Timestamp not within time limit.", "timestamp", alexaRequest.Request.Timestamp, "difference", math.Abs(time.Since(timestamp).Seconds()))
http.Error(w, "Timestamp not within time limit", http.StatusBadRequest)
return
}
output, e := json.Marshal(h.Skill.ProcessRequest(&alexaRequest))
if e != nil {
h.Log.Errorw("Error while marshalling response", "error", e)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write(output)
}