/
wpp.go
104 lines (79 loc) · 2.35 KB
/
wpp.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
package main
import (
"encoding/json"
"flag"
"github.com/garyburd/redigo/redis"
"io/ioutil"
"log"
"net/http"
)
var addr = flag.String("addr", ":8080", "http service address")
var pool = &redis.Pool{MaxIdle: 3, Dial: func() (redis.Conn, error) { return redis.Dial("tcp", ":6379") }}
var scripts = make(map[string]*redis.Script)
type Company struct {
Name string `redis:"name" json:"name"`
Website string `redis:"website" json:"website"`
Description string `redis:"description" json:"description"`
Languages []string `redis:"languages" json:"languages"`
Frameworks []string `redis:"frameworks" json:"frameworks"`
}
type Tool struct {
Name string `json:"name"`
Count int `json:"count"`
}
func main() {
flag.Parse()
loadScripts()
http.HandleFunc("/", indexHandler)
http.HandleFunc("/api", companyListHandler)
log.Fatal(http.ListenAndServe(*addr, nil))
}
func loadScripts() {
scriptNames, err := ioutil.ReadDir("lua")
if err != nil {
log.Fatal("could not load lua scripts: ", err)
}
for _, s := range scriptNames {
scriptName := s.Name()
scriptData, err := ioutil.ReadFile("lua/" + scriptName)
if err != nil {
log.Fatal("could not load lua script: ", err)
}
log.Println("loaded script: ", scriptName)
scripts[scriptName] = redis.NewScript(-1, string(scriptData))
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/" {
http.Redirect(w, r, "/", 301)
return
}
http.ServeFile(w, r, "index.html")
}
func companyListHandler(w http.ResponseWriter, r *http.Request) {
conn := pool.Get()
defer conn.Close()
data, err := redis.Values(scripts["get_companies.lua"].Do(conn, 0))
if err != nil {
log.Print("failed to get companies: ", err)
w.WriteHeader(500)
return
}
companies := make([]*Company, 0, len(data))
for _, companyData := range data {
company := &Company{}
//get the key/val data about the company
redis.ScanStruct(companyData.([]interface{})[0].([]interface{}), company)
//get the tools
company.Languages, _ = redis.Strings(companyData.([]interface{})[1], nil)
company.Frameworks, _ = redis.Strings(companyData.([]interface{})[2], nil)
companies = append(companies, company)
}
companiesJSON, err := json.Marshal(companies)
if err != nil {
log.Print("failed to serialize companies: ", err)
w.WriteHeader(500)
return
}
w.Write(companiesJSON)
}