/
main.go
82 lines (67 loc) · 2 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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/go-redis/redis"
"github.com/google/uuid"
)
func main() {
log.SetOutput(os.Stdout)
//HTTP server as per kubeless spec
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second) //just some time to connect to REDIS...
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
http.HandleFunc("/storejson", Handler)
log.Fatalf("error running server: %v", http.ListenAndServe(":8080", nil))
}
// Handler is the fission handler
func Handler(w http.ResponseWriter, r *http.Request) {
redisClient, err := client(os.Getenv("REDIS_SERVER_ADDR"), os.Getenv("REDIS_SERVER_PWD"))
if err != nil {
http.Error(w, fmt.Sprintf("could not connect to REDIS: %v", err), http.StatusInternalServerError)
log.Fatalf("error connecting to REDIS: %v", err)
return
}
httpBody, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, fmt.Sprintf("could not read request body: %v", err), http.StatusInternalServerError)
return
}
payload := make(map[string]interface{}, 0)
payload["timestamp_ns"] = time.Now().UnixNano()
payload["request_body"] = httpBody
jsonBytes, err := json.Marshal(&payload)
if err != nil {
http.Error(w, fmt.Sprintf("failed to marshal data structure: %v", err), http.StatusInternalServerError)
return
}
if err := saveAnalytics(redisClient, jsonBytes); err != nil {
http.Error(w, fmt.Sprintf("failed to store request: %v", err), http.StatusInternalServerError)
return
}
return
}
func client(address, password string) (*redis.Client, error) {
client := redis.NewClient(&redis.Options{
Addr: address,
Password: password, // no password set
DB: 0, // use default DB
})
_, err := client.Ping().Result()
if err != nil {
return nil, err
}
return client, err
}
func saveAnalytics(client *redis.Client, payload []byte) error {
id := uuid.New()
status := client.Set(id.String(), payload, 24*time.Hour)
return status.Err()
}