-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclickstream-feeder.go
81 lines (70 loc) · 2.19 KB
/
clickstream-feeder.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 ClickStreamFeeder
import (
"fmt"
"errors"
"strings"
"strconv"
"net/url"
"net/http"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
)
func init() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
qValues, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
fmt.Fprint(w, "did not send properly formatted query string: " + err.Error())
w.WriteHeader(http.StatusBadRequest)
} else {
err = ValidateQueryString(qValues)
if err != nil {
fmt.Fprint(w, "did not send all required paramters: " + err.Error())
w.WriteHeader(http.StatusBadRequest)
} else {
err = SendClickstreams(qValues, r, w)
if err != nil {
fmt.Fprint(w, "did not post data: " + err.Error() + "\n")
w.WriteHeader(http.StatusBadRequest)
} else {
fmt.Fprint(w, "Request received and processed. Data should show up momentarily\n")
}
}
}
}
// parameter validation
func ValidateQueryString(queryParams url.Values) (error) {
_, targetOK := queryParams["targetURI"]
_, countOK := queryParams["count"]
_, prefixOK := queryParams["prefix"]
if !countOK {
return errors.New("Did not include count\n")
}
if !targetOK {
return errors.New("Did not include targetURI\n")
}
if !prefixOK {
return errors.New("Did not include prefix\n")
}
return nil
}
func SendClickstreams(qValues url.Values, r *http.Request, w http.ResponseWriter) (error) {
countStr := qValues.Get("count")
count, _ := strconv.Atoi(countStr)
targetURI := qValues.Get("targetURI")
prefix := qValues.Get("prefix")
var err error
for i := 0; i < count; i++ {
iStr := strconv.Itoa(i)
req, _ := http.NewRequest("POST", targetURI, strings.NewReader("{\"body\":\""+ prefix + "-" + iStr + "\"}"))
req.Header.Set("Content-Type", "application/json")
c := appengine.NewContext(r)
client := urlfetch.Client(c)
_, err = client.Do(req)
if err != nil {
break
}
}
return err
}