-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.go
More file actions
84 lines (70 loc) · 1.72 KB
/
main.go
File metadata and controls
84 lines (70 loc) · 1.72 KB
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
package main
import (
"database/sql"
"log"
"net/http"
"strconv"
"strings"
"github.com/kiasaki/batbelt/http/middlewares"
"github.com/kiasaki/batbelt/http/mm"
"github.com/kiasaki/marks/data"
)
var db *sql.DB
func SetDB(d *sql.DB) {
db = d
}
func DB() *sql.DB {
return db
}
// Entrypoint
func main() {
SetCfg(ParseFlag())
SetDB(data.Connect(Cfg().PostgresURL))
if Cfg().CreateDb {
createDb()
} else {
handleHTTP()
}
}
func handleHTTP() {
registerHandlers()
var stringPort = strconv.Itoa(Cfg().Port)
log.Println("Started listening on port " + stringPort)
log.Fatal(http.ListenAndServe(":"+stringPort, nil))
}
func registerHandlers() {
mmChain := mm.New(middlewares.LogWithTiming)
// Add basic auth middleware if configuration specifies user & pass
u, p := Cfg().BasicAuthUser, Cfg().BasicAuthPass
if u != "" && p != "" {
mmChain = mmChain.Append(middlewares.BasicAuth(u, p))
}
http.Handle("/", mmChain.Then(http.HandlerFunc(routeRequest)))
}
func routeRequest(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/new", 302)
} else if r.URL.Path == "/styles.css" {
w.Header().Set("Content-Type", "text/css")
w.Write([]byte(stylesContents))
} else if r.URL.Path == "/new" {
if r.Method != "POST" {
handleNewPage(w, r)
} else {
handleNewPagePost(w, r)
}
} else if r.URL.Path[:3] == "/n/" && strings.HasSuffix(r.URL.Path, "/delete") {
handleDeletePage(w, r)
} else if r.URL.Path[:3] == "/n/" && strings.HasSuffix(r.URL.Path, "/edit") {
if r.Method != "POST" {
handleEditPage(w, r)
} else {
handleEditPagePost(w, r)
}
} else if r.URL.Path[:3] == "/n/" {
handleViewPage(w, r)
} else {
w.WriteHeader(404)
w.Write([]byte("404 - Page not found"))
}
}