forked from clayallsopp/readme-score-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
72 lines (64 loc) · 1.66 KB
/
server.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
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
"github.com/go-martini/martini"
"github.com/martini-contrib/cors"
"github.com/soveran/redisurl"
"os"
"time"
)
type Server struct {
Pool *redis.Pool
Martini *martini.ClassicMartini
}
func (server *Server) RedisAddress() string {
redisAddress := os.Getenv("REDIS_URL")
if redisAddress == "" {
redisAddress = os.Getenv("REDISCLOUD_URL")
if redisAddress == "" {
redisAddress = "redis://localhost:6379"
}
}
return redisAddress
}
func (server *Server) CreatePool() {
server.Pool = &redis.Pool{
MaxActive: 10,
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
fmt.Println("Connecting to " + server.RedisAddress())
return redisurl.ConnectToURL(server.RedisAddress())
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
func (server *Server) Redis(commandName string, args ...interface{}) (reply interface{}, err error) {
conn := server.Pool.Get()
defer conn.Close()
return conn.Do(commandName, args...)
}
func (server *Server) CreateMartini() {
fmt.Println(&server)
server.Martini = martini.Classic()
server.Martini.Use(cors.Allow(&cors.Options{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET"},
ExposeHeaders: []string{"Content-Type, Cache-Control, Expires, Etag, Last-Modified"},
AllowCredentials: true,
}))
server.Martini.Get("/score(\\.(?P<format>json|html|svg|txt))?", server.GetScore)
}
func (server *Server) Run() {
fmt.Println(&server)
server.Martini.Run()
}
func (server *Server) Start() {
server.CreatePool()
server.CreateMartini()
server.Run()
}