-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
190 lines (159 loc) · 5.11 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
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/gorilla/mux"
"github.com/k0kubun/pp"
_ "github.com/lib/pq"
)
var (
db *sql.DB
defaultPer = 10
stmtGetCountry *sql.Stmt
stmtGetCountries *sql.Stmt
httpSocket = "localhost:8080"
)
func init() {
s := os.Getenv("HTTP_SOCKET")
if s != "" {
httpSocket = s
}
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/addresses", http.StatusFound)
}
func setupDB() {
dsn := fmt.Sprintf("host=%s dbname=%s user=%s port=%s sslmode=disable",
mustGetenv("PGHOST"),
mustGetenv("PGDATABASE"),
mustGetenv("PGUSER"),
mustGetenv("PGPORT"),
)
log.Printf("dsn: \"%s\"\n", dsn)
var err error
db, err = sql.Open("postgres", dsn)
if err != nil {
log.Fatal(err)
}
err = db.Ping()
if err != nil {
log.Fatal(err)
}
}
func injectKey(fn func(http.ResponseWriter, *http.Request, string), path string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "*****path=%s******\r\n", path)
key := r.URL.Path[len(path):]
fn(w, r, key)
}
}
func route(fn func(http.ResponseWriter, *http.Request, string), basePath string) http.HandlerFunc {
pp.Println("basePath =", basePath)
return func(w http.ResponseWriter, r *http.Request) {
key := r.URL.Path[len(basePath):]
fn(w, r, key)
}
}
func timerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//fmt.Println("Before:", time.Now())
next.ServeHTTP(w, r)
//fmt.Println("After:", time.Now())
})
}
func mustGetenv(env string) string {
s := os.Getenv(env)
if s == "" {
panic(fmt.Sprintf("%s env var not set", env))
}
return s
}
func stringKeyProvider(key string, fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
k, ok := vars[key]
if !ok {
log.Printf("stringKeyProvider: key '%s' not found\n", key)
httpGenericErr(w)
} else {
fn(w, r, k)
}
}
}
func intKeyProvider(key string, fn func(http.ResponseWriter, *http.Request, int)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
k, ok := vars[key]
if !ok {
log.Printf("intKeyProvider: key '%s' not found\n", key)
httpGenericErr(w)
} else {
n, err := strconv.Atoi(k)
if err != nil {
log.Println(err)
httpGenericErr(w)
return
}
fn(w, r, n)
}
}
}
// Injects middlewares while routing
type routerHelper struct {
mux *mux.Router
middlewareChain func(h http.Handler) http.Handler
}
func (r *routerHelper) HandleFunc(pat string, h http.HandlerFunc) *mux.Route {
return r.mux.Handle(pat, r.middlewareChain(h))
}
func main() {
setupDB()
defer db.Close()
mux := mux.NewRouter()
r := &routerHelper{
mux: mux,
middlewareChain: middlewares,
}
/*
rr := &routerHelper{
mux: mux,
middlewareChain: func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "rr middleware chain!!")
next.ServeHTTP(w, r)
})
},
}
r.mux.HandleFunc("/countries/new", newCountry).Methods("GET") // no middlewares
rr.mux.HandleFunc("/countries/new", newCountry).Methods("GET") // another middleware
*/
// http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
// http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("public/assets"))))
http.Handle("/assets/", middlewares(http.FileServer(http.Dir("public"))))
// http.Handle("/assets/", http.StripPrefix("public/assets", http.FileServer(http.Dir("public/assets"))))
if os.Getenv("DEV") == "1" {
http.Handle("/assets_dev/", http.StripPrefix("/assets_dev/", http.FileServer(http.Dir("assets"))))
}
r.HandleFunc("/", rootHandler).Methods("GET")
// r.HandleFunc("/countries", indexCountries).Methods("GET")
// r.HandleFunc("/countries/{id}", intKeyProvider("id", showCountry)).Methods("GET")
// r.HandleFunc("/countries", createCountry).Methods("POST")
// r.HandleFunc("/countries/{id}", intKeyProvider("id", updateCountry)).Methods("PUT", "PATCH")
r.HandleFunc("/api/addresses", apiIndexAddresses).Methods("GET")
r.HandleFunc("/addresses", indexAddresses).Methods("GET")
// r.HandleFunc("/countries/{id}/contracts/new", newCountry).Methods("GET")
// r.HandleFunc("/countries/{id}/stats", intKeyProvider("id", showCountryStats)).Methods("GET")
// r.HandleFunc("/countries/{id}/cities", intKeyProvider("id", indexCountryCities)).Methods("GET")
// r.HandleFunc("/countries/{country_id}/cities/new", intKeyProvider("country_id", newCity)).Methods("GET")
// r.HandleFunc("/cities/{id}/edit", intKeyProvider("id", editCity)).Methods("GET")
// r.HandleFunc("/cities/{id}", intKeyProvider("id", showCity)).Methods("GET")
// r.HandleFunc("/cities/{id}", intKeyProvider("id", updateCity)).Methods("PUT", "PATCH")
// r.HandleFunc("/cities", createCity).Methods("POST")
http.Handle("/", redirectOnTrailingSlash(r.mux))
log.Println("Running on " + httpSocket)
log.Fatal(http.ListenAndServe(httpSocket, nil))
}