-
Notifications
You must be signed in to change notification settings - Fork 0
/
inboundhandler.go
80 lines (72 loc) · 2 KB
/
inboundhandler.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/bikedataproject/go-bike-data-lib/strava"
log "github.com/sirupsen/logrus"
)
// ResponseMessage : General response to send on requests
type ResponseMessage struct {
Message string `json:"message"`
}
// SendJSONResponse : Send a struct as JSON response
func SendJSONResponse(w http.ResponseWriter, obj interface{}) {
response, err := json.Marshal(&obj)
if err != nil {
log.Fatalf("Could not parse response: %v", err)
} else {
fmt.Fprintf(w, string(response))
}
}
// HandleStravaWebhook : Handle incoming requests from Strava
func HandleStravaWebhook(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
defer r.Body.Close()
// Decode the JSON body as struct
var msg StravaWebhookMessage
if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
SendJSONResponse(w, ResponseMessage{
Message: "Could not decode JSON body",
})
} else {
// Get activity data
if err := msg.WriteToDatabase(); err != nil {
log.Warnf("Could not get activity data: %v", err)
} else {
}
SendJSONResponse(w, ResponseMessage{
Message: "Ok",
})
}
break
case "GET":
// Try to fetch a message from Strava
challenge, err := getURLParam("hub.challenge", r)
if err != nil {
log.Warn("Could not get hub challenge from URL params")
} else {
log.Info("Received valid Strava verification request")
msg := strava.WebhookValidationRequest{
HubChallenge: challenge,
}
SendJSONResponse(w, msg)
}
break
default:
log.Warnf("Received a HTTP %s request instead of GET or POST on webhook handler", r.Method)
SendJSONResponse(w, ResponseMessage{
Message: fmt.Sprintf("Use HTTP POST or HTTP GET instead of %v", r.Method),
})
break
}
}
// getURLParam : Request a parameter from the URL
func getURLParam(paramName string, request *http.Request) (result string, err error) {
result = request.URL.Query()[paramName][0]
if result == "" {
err = fmt.Errorf("Param not found in URL")
}
return
}