forked from iron-io/functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
function.go
76 lines (64 loc) · 1.42 KB
/
function.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/garyburd/redigo/redis"
)
type payload struct {
Key string `json:"key"`
Value string `json:"value"`
}
func main() {
// Getting stdin
plStdin, _ := ioutil.ReadAll(os.Stdin)
// Transforming JSON to a *payload
var pl payload
err := json.Unmarshal(plStdin, &pl)
if err != nil {
log.Println("Invalid payload")
log.Fatal(err)
return
}
// Dialing redis server
c, err := redis.Dial("tcp", os.Getenv("SERVER"))
if err != nil {
log.Println("Failed to dial redis server")
log.Fatal(err)
return
}
// Authenticate to redis server if exists the password
if os.Getenv("REDIS_AUTH") != "" {
if _, err := c.Do("AUTH", os.Getenv("REDIS_AUTH")); err != nil {
log.Println("Failed to authenticate to redis server")
log.Fatal(err)
return
}
}
// Check if payload command is valid
if os.Getenv("COMMAND") != "GET" && os.Getenv("COMMAND") != "SET" {
log.Println("Invalid command")
return
}
// Execute command on redis server
var r interface{}
if os.Getenv("COMMAND") == "GET" {
r, err = c.Do("GET", pl.Key)
} else if os.Getenv("COMMAND") == "SET" {
r, err = c.Do("SET", pl.Key, pl.Value)
}
if err != nil {
log.Println("Failed to execute command on redis server")
log.Fatal(err)
return
}
// Convert reply to string
res, err := redis.String(r, err)
if err != nil {
return
}
// Print reply
fmt.Println(res)
}