/
api.go
88 lines (77 loc) · 1.86 KB
/
api.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
package main
import (
"encoding/json"
"fmt"
"github.com/codegangsta/martini-contrib/render"
rethink "github.com/dancannon/gorethink"
"github.com/go-martini/martini"
"net/http"
"strings"
)
var session *rethink.Session
// Struct tags are used to map struct fields to fields in the database
type Log struct {
Id string `gorethink:"id,omitempty"`
AppName string `gorethink:"AppName"`
Message string `gorethink:"Message"`
Ip string
}
// TODO sucks, need to use the same session than the one declared in main.go
func init() {
var err error
session, err = rethink.Connect(rethink.ConnectOpts{
Address: "localhost:28015",
Database: "logs",
})
if err != nil {
fmt.Println(err)
return
}
}
func onChange() {
res, err := rethink.Table("exceptions").Changes().Run(session)
if err != nil {
fmt.Println(err.Error())
}
// Use goroutine to wait for changes. Prints the first 10 results
go func() {
var response interface{}
for res.Next(&response) {
fmt.Println("okkkkk")
}
if res.Err() != nil {
fmt.Println(res.Err())
}
}()
}
// TODO separate view from *model*
func NewLog(log Log, req *http.Request, args martini.Params, r render.Render) {
ip := strings.Split(req.RemoteAddr, ":")[0]
log.Ip = ip
result, err := rethink.Table("exceptions").Insert(log).RunWrite(session)
if err != nil {
fmt.Println(err)
}
key := result.GeneratedKeys[0]
b, err := json.Marshal(log)
broadcastMessage(1, b)
r.JSON(200, map[string]interface{}{"key": key})
}
// Get all log with appname passed in params
func GetLogForApp(appname string) (logs []Log, err error) {
rows, err := rethink.Table("exceptions").Filter(map[string]interface{}{
"AppName": appname,
}).Limit(10).Run(session)
if err != nil {
fmt.Println(err)
return nil, err
}
err2 := rows.All(&logs)
if err2 != nil {
return nil, err
}
if logs == nil {
return nil, err
}
return logs, nil
}