-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
110 lines (91 loc) · 2.2 KB
/
handlers.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
package main
import (
"encoding/json"
"fmt"
"gopkg.in/mgo.v2/bson"
"io"
"io/ioutil"
"math/rand"
"net/http"
"time"
"github.com/gorilla/mux"
)
type Token struct {
Id string `bson:"_id", json:"token"`
Created time.Time
}
type TokenRes struct {
Id bson.ObjectId `bson:"_id", json:"_id"`
Token string `json:"token"`
}
type Confession struct {
Confession string `json:"confession"`
}
type ConfessionRes struct {
Id bson.ObjectId `bson:"_id", json:"_id"`
Confession string `json:"confession"`
}
func CreateToken() Token {
// generate new token
id := shortId(4)
token := Token{
id,
time.Now(),
}
// ensure token id doesn't exist
err := tokens.Find(bson.M{"_id": id}).One(&token)
if err == nil {
token = CreateToken()
return token
} else {
return token
}
}
func GetConfessionToken(w http.ResponseWriter, r *http.Request) {
res := CreateToken()
// save token
err := tokens.Insert(&res)
if err != nil {
panic(err)
}
// respond
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(res)
}
func Confess(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
token := vars["token"]
tokenRes := TokenRes{}
confession := Confession{}
confessionRes := ConfessionRes{}
confessions := db.C("confessions")
err := tokens.Find(bson.M{"_id": token}).One(&tokenRes)
if err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(404)
json.NewEncoder(w).Encode("Token not found")
} else {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
if err := json.Unmarshal(body, &confession); err != nil {
panic(err)
}
count, err := confessions.Find(nil).Count()
randn := rand.Intn(count)
fmt.Println(count)
fmt.Println(randn)
confessions.Find(nil).Skip(randn).One(&confessionRes)
// remove access token and response confession
confessions.RemoveId(confessionRes.Id)
tokens.RemoveId(tokenRes.Id)
confessions.Insert(confession)
// send response
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(confessionRes)
}
}