-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
72 lines (56 loc) · 1.71 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 heyfyiserver
import (
"encoding/gob"
"encoding/json"
"html/template"
"log"
"net/http"
"reflect"
"strconv"
"time"
"github.com/gocraft/web"
"github.com/gorilla/schema"
"github.com/gorilla/sessions"
"github.com/kiwih/heyfyi/heyfyiserver/fact"
"github.com/kiwih/heyfyi/heyfyiserver/fyidb"
)
var (
store *sessions.CookieStore
templates = template.Must(template.New("").Funcs(funcMap).ParseGlob("./media/templates/*")) //this initializes the template engine
decoder = schema.NewDecoder() //this initializes the schema (HTML form decoding) engine
)
func StartServer(serverAddress string, cookieStoreSalt string) {
//gob is used when we save failed form structs to the session
gob.Register(CreateAccount{})
gob.Register(fact.Fact{})
decoder.RegisterConverter(false, ConvertBool)
fyidb.ConnectDatabase("heyfyi")
store = sessions.NewCookieStore([]byte(cookieStoreSalt))
router := initRouter()
go BackgroundVoteGiver()
log.Println("Server running at " + serverAddress)
if err := http.ListenAndServe(serverAddress, router); err != nil {
log.Println("Error:", err.Error())
}
}
func ConvertBool(value string) reflect.Value {
if value == "on" {
return reflect.ValueOf(true)
} else if v, err := strconv.ParseBool(value); err == nil {
return reflect.ValueOf(v)
}
return reflect.ValueOf(false)
}
func ReturnJSON(rw web.ResponseWriter, object interface{}) {
j, err := json.MarshalIndent(object, "", "\t")
if err != nil {
http.Error(rw, "500: "+err.Error(), http.StatusInternalServerError)
return
}
rw.Write(j)
}
func BackgroundVoteGiver() {
fyidb.DbStorage.GiveOneVoteToAllAccounts()
time.Sleep(3600 * time.Second)
BackgroundVoteGiver()
}