/
server.go
195 lines (159 loc) · 4.34 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
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
package main
import (
"bufio"
"encoding/json"
"errors"
"flag"
"fmt"
"howtotip/helpers"
"howtotip/models"
"html/template"
"log"
"net/http"
"os"
"path"
"reflect"
"strings"
"time"
)
const dateFmt = "2006-01-02"
const timeFmt = "2006-01-02 15:04:05"
type config map[string]string
func jsonResponder(w http.ResponseWriter, r *http.Request, data interface{}, err error) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
if err != nil {
http.Error(w, "", http.StatusBadRequest)
enc.Encode(map[string]string{"error": err.Error()})
} else {
kind := reflect.TypeOf(data).Kind()
if (kind == reflect.Slice || kind == reflect.Map || kind == reflect.Ptr) && reflect.ValueOf(data).IsNil() {
if kind == reflect.Slice {
fmt.Fprintf(w, "[]")
} else {
fmt.Fprintf(w, "{}")
}
} else {
enc.Encode(data)
}
}
}
func successResponder(w http.ResponseWriter, r *http.Request, err error) {
jsonResponder(w, r, map[string]bool{"success": err == nil}, err)
}
func countriesHandler(w http.ResponseWriter, r *http.Request) {
var err error
var data []models.Country
defer func() { jsonResponder(w, r, data, err) }()
data = models.GetCountries()
}
func countryHandler(w http.ResponseWriter, r *http.Request) {
var err error
var data models.Country
defer func() { jsonResponder(w, r, data, err) }()
r.ParseForm()
slug := r.FormValue("slug")
if slug == "" {
return
}
data = models.GetCountry(slug)
}
type PageData struct {
Countries []models.Country
Data interface{}
Year string
}
func pageHandler(w http.ResponseWriter, r *http.Request) {
var name string
var data interface{}
if r.URL.Path == "/" {
name = "home"
} else {
name = "country"
slug := strings.Split(r.URL.Path, "/")[1]
data = models.GetCountry(slug)
}
countries := models.GetCountries()
t := time.Now()
year := t.Format("2006")
pageData := PageData{
countries,
data,
year,
}
layout := path.Join("templates", "layout.html")
toolbar := path.Join("templates", "_toolbar.html")
page := path.Join("templates", fmt.Sprintf("%s.html", name))
tmpl, _ := template.ParseFiles(layout, page, toolbar)
tmpl.ExecuteTemplate(w, "layout", &pageData)
}
func routeHandler(router helpers.RegexpRouter) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
router.ServeHTTP(w, r)
log.Printf("%s %s %s %v", r.RemoteAddr, r.Method, r.URL, time.Since(start))
})
}
func readConfig(filename string) (map[string]string, error) {
config := map[string]string{
"dbhost": "localhost",
}
file, err := os.Open(filename)
if err != nil {
return nil, errors.New("Couldn't read config " + filename)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(strings.SplitN(scanner.Text(), "#", 2)[0])
if line == "" {
continue
}
pieces := strings.SplitN(line, "=", 2)
if len(pieces) != 2 {
return nil, errors.New(fmt.Sprintf("Couldn't parse line \"%s\"", line))
}
config[strings.TrimSpace(pieces[0])] = strings.TrimSpace(pieces[1])
}
return config, nil
}
func main() {
var err error
var config_file string
flag.StringVar(&config_file, "config", "./config.cfg", "config file location")
flag.Parse()
cfg, err := readConfig(fmt.Sprintf("%v", config_file))
if err != nil {
log.Fatal(err.Error())
}
if lf := cfg["log_file"]; lf != "" {
logfile, err := os.OpenFile(lf, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.FileMode(0666))
if err != nil {
log.Println(err.Error())
} else {
log.SetOutput(logfile)
}
}
if pidfile := cfg["pid_file"]; pidfile != "" {
file, err := os.Create(pidfile)
if err != nil {
log.Fatal(err.Error())
}
file.WriteString(fmt.Sprintln(os.Getpid()))
file.Close()
}
models.ConnectDB(cfg["dbhost"], cfg["dbport"], cfg["dbuser"], cfg["dbpass"], cfg["dbname"])
assetServer := http.FileServer(http.Dir("assets"))
http.Handle("/assets/", http.StripPrefix("/assets/", assetServer))
router := new(helpers.RegexpRouter)
router.AddRoute("/api/countries.json", countriesHandler)
router.AddRoute("/api/countries/show.json", countryHandler)
router.AddRoute("/.*", pageHandler)
http.Handle("/", routeHandler(*router))
listen := "127.0.0.1:8080"
fmt.Println(fmt.Sprintf("listening on %s", listen))
err = http.ListenAndServe(listen, nil)
if err != nil {
panic("http.ListenAndServe: " + err.Error())
}
}