-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
101 lines (83 loc) · 2.28 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"strconv"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/bcneng/twitter-contest/twitter"
"github.com/sirupsen/logrus"
)
func handler(request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
if os.Getenv("TWITTERCONTEST_BEARER_TOKEN") != strings.TrimPrefix(request.Headers["authorization"], "Bearer ") {
return &events.APIGatewayProxyResponse{
StatusCode: 401,
IsBase64Encoded: false,
}, nil
}
apiKey, err := getQueryParam(request, "api_key", true)
if err != nil {
return nil, err
}
apiKeySecret, err := getQueryParam(request, "api_key_secret", true)
if err != nil {
return nil, err
}
tweetIDStr, err := getQueryParam(request, "tweet_id", true)
if err != nil {
return nil, err
}
tweetID, err := strconv.Atoi(tweetIDStr)
if err != nil {
return nil, errors.New("tweet_id should be a valid integer")
}
pickStr, err := getQueryParam(request, "pick", true)
if err != nil {
return nil, err
}
pick, err := strconv.Atoi(pickStr)
if err != nil {
return nil, errors.New("pick should be a valid integer")
}
// If not set, will use the account author of the tweet
account, err := getQueryParam(request, "account_to_follow", false)
if err != nil {
return nil, err
}
account = strings.TrimPrefix(account, "@")
result, err := twitter.Contest(twitter.Credentials{
APIKey: apiKey,
APIKeySecret: apiKeySecret,
}, tweetID, pick, account)
if err != nil {
return nil, err
}
if len(result.Winners) > 0 {
logrus.WithField("winners", result.Winners).Infoln("found winners!")
} else {
logrus.Infoln("could not find winners")
}
encodedBody, err := json.Marshal(result)
if err != nil {
return nil, err
}
return &events.APIGatewayProxyResponse{
StatusCode: 200,
Headers: map[string]string{"Content-Type": "application/json"},
Body: string(encodedBody),
IsBase64Encoded: false,
}, nil
}
func main() {
lambda.Start(handler)
}
func getQueryParam(request events.APIGatewayProxyRequest, name string, required bool) (string, error) {
val, ok := request.QueryStringParameters[name]
if required && !ok {
return "", fmt.Errorf("%q query param is mandatory", name)
}
return val, nil
}