-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdb.go
More file actions
87 lines (74 loc) · 2 KB
/
db.go
File metadata and controls
87 lines (74 loc) · 2 KB
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
package main
import (
"encoding/json"
"strconv"
"log"
"time"
"errors"
"math/rand"
"os"
redigo "github.com/gomodule/redigo/redis"
)
var redisPool *redigo.Pool
func init() {
log.Printf("Opening Redis: %s", os.Getenv("REDIS_ADDRESS"))
redisPool = &redigo.Pool{
MaxIdle: 10,
IdleTimeout: 1 * time.Second,
Dial: func() (redigo.Conn, error) {
return redigo.Dial("tcp", os.Getenv("REDIS_ADDRESS"))
},
TestOnBorrow: func(c redigo.Conn, t time.Time) (err error) {
_, err = c.Do("PING")
if err != nil {
panic("Error connecting to redis")
}
return
},
}
}
func getFileListByZipReferenceId(id string) (files []*ZipEntry, err error) {
redis := redisPool.Get()
defer redis.Close()
// Get the value from Redis
result, err := redis.Do("GET", "zip:" + id)
if err != nil || result == nil {
err = errors.New("Access Denied (sorry your link has timed out)")
return
}
// Convert to bytes
var resultByte []byte
var ok bool
if resultByte, ok = result.([]byte); !ok {
err = errors.New("Error converting data stream to bytes")
return
}
// Decode JSON
if err = json.Unmarshal(resultByte, &files); err != nil {
err = errors.New("Error decoding json: " + string(resultByte))
}
return
}
func CreateZipReference(files []*ZipEntry) (ref_id_string string) {
redis := redisPool.Get()
defer redis.Close()
filesJson, err := json.Marshal(files)
HandleError(err)
//get new id redis
ref_id, err := redis.Do("INCR", "zip_reference_id")
HandleError(err)
ref_id_string = RandomString(5) + strconv.FormatInt(ref_id.(int64), 10)
// Save JSON files to Redis
_, err = redis.Do("SET", "zip:" + ref_id_string, filesJson)
HandleError(err)
return
}
func RandomString(strlen int) string {
rand.Seed(time.Now().UTC().UnixNano())
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
result := make([]byte, strlen)
for i := 0; i < strlen; i++ {
result[i] = chars[rand.Intn(len(chars))]
}
return string(result)
}