-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
209 lines (193 loc) · 5.1 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main
import (
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/skratchdot/open-golang/open"
)
var (
flagListen = flag.String("l", "8080", "Used to define which port is listened on.")
dbToUse = flag.String("db", "scribble", "Used to define which poll storage is used")
logs = flag.Bool("showlogs", false, "set to show logs.Other wise now logs.")
autoopen = flag.Bool("dontopen", false, "Don't Autoopen polls")
t = template.Must(getTemplates())
polls PollStorer
)
func init() {
flag.Parse()
log.SetFlags(log.Lshortfile)
if !*logs {
log.SetOutput(ioutil.Discard)
}
switch *dbToUse {
case "inmemory":
polls = &inMemoryPollStore{make(map[int]*Poll)}
case "scribble":
polls = NewScribbleStorer()
case "sqlite":
var err error
polls, err = NewDbPollStore()
if err != nil {
panic(err)
}
default:
log.Fatalln("Invalid db type: ", *dbToUse)
}
go func() {
for {
time.Sleep(time.Second)
temp, err := getTemplates()
if err != nil {
log.Println(err)
continue
}
t = temp
}
}()
}
func getTemplates() (*template.Template, error) {
files, err := AssetDir("view")
if err != nil {
return nil, err
}
temp := template.New("base")
for _, f := range files {
data, err := Asset("view/" + f)
if err != nil {
return nil, err
}
temp, err = temp.Parse(string(data))
if err != nil {
return nil, err
}
}
return temp, nil
}
func main() {
log.Println("Starting with PID:", os.Getpid(), "Current version:", version, os.Args)
r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/", makePoll)
r.HandleFunc("/newpoll/", newPoll)
r.HandleFunc("/poll/{id:[0-9]+}/", viewPoll).Methods("GET")
r.HandleFunc("/poll/{id:[0-9]+}/vote/", votePoll).Methods("POST")
r.HandleFunc("/poll/{id:[0-9]+}/r/", pollResults).Methods("GET")
if !strings.HasPrefix(*flagListen, ":") {
*flagListen = fmt.Sprintf(":%s", *flagListen)
}
if !*autoopen {
go open.Start("http://localhost" + *flagListen)
}
log.Println("Starting on port: ", *flagListen)
err := http.ListenAndServe(*flagListen, r)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, *flagListen)
}
}
func viewPoll(w http.ResponseWriter, req *http.Request) {
log.Println("Viewing poll.")
pollID, err := strconv.Atoi(mux.Vars(req)["id"])
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
thePoll, ok := polls.Get(pollID)
if !ok {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
err = t.ExecuteTemplate(w, "poll", thePoll) // merge.
if err != nil {
log.Println(err)
}
}
func pollResults(w http.ResponseWriter, req *http.Request) {
err := req.ParseForm()
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
pollID, err := strconv.Atoi(mux.Vars(req)["id"])
if err != nil {
log.Println("failed to parse poll id")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
thePoll, got := polls.Get(pollID)
if !got {
log.Println("failed to get poll")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
thePoll.AlreadyVoted = req.URL.Query().Get("alreadyVoted") == "true"
if thePoll.AlreadyVoted {
thePoll.IP = req.RemoteAddr
} else {
thePoll.IP = ""
}
err = t.ExecuteTemplate(w, "results", thePoll) // merge.
if err != nil {
log.Println(err)
fmt.Fprintln(w, err.Error())
}
}
func votePoll(w http.ResponseWriter, req *http.Request) {
log.Println("Voting")
err := req.ParseForm()
if err != nil {
fmt.Fprintf(w, "Nope dip")
}
vars := mux.Vars(req)
pollID, err := strconv.Atoi(vars["id"])
if err != nil {
panic("shit")
}
n, err := strconv.Atoi(req.PostFormValue("Answer"))
if err != nil {
http.Error(w, "Invalid answer", http.StatusBadRequest)
return
}
voted := polls.Vote(pollID, n, strings.Split(req.RemoteAddr, ":")[0])
if !voted {
log.Println("Unable to vote. Probably already voted: " + req.RemoteAddr)
http.Redirect(w, req, fmt.Sprintf("/poll/%d/r/?alreadyVoted=true", pollID), http.StatusSeeOther)
return
}
http.Redirect(w, req, fmt.Sprintf("/poll/%d/r/", pollID), http.StatusSeeOther)
}
func newPoll(w http.ResponseWriter, req *http.Request) {
err := req.ParseForm()
if err != nil {
fmt.Fprintf(w, "Nope dip")
}
p := NewPoll(req.PostFormValue("question"), req.Form["option"], req.PostFormValue("PerIP") == "on")
id, err := polls.New(p)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, req, fmt.Sprintf("/poll/%d/", id), http.StatusSeeOther)
log.Println("New poll made")
}
func makePoll(w http.ResponseWriter, req *http.Request) {
t.ExecuteTemplate(w, "main", nil) // merge.
}
func answerStringsToAnswers(theStrings []string) []Answer {
nonblank := []Answer{}
for _, aString := range theStrings {
if len(aString) > 0 {
nonblank = append(nonblank, Answer{Value: aString, Total: 0})
}
}
return nonblank
}