-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
203 lines (180 loc) · 5.83 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
191
192
193
194
195
196
197
198
199
200
201
202
203
package main
import (
"database/sql"
"errors"
"fmt"
"html/template"
"net/http"
"os"
"regexp"
"time"
_ "github.com/lib/pq"
"github.com/alecthomas/kingpin"
"github.com/julienschmidt/httprouter"
log "github.com/sirupsen/logrus"
)
const (
LOGGING_DATE_FORMAT = "Mon Jan 2 15:04:05 2006"
)
var validGetPath = regexp.MustCompile("^/(index|404|math)$")
type Controller struct {
templates *template.Template
templateDir string
staticDir string
}
type PSQLLogHook struct {
tableName string
DB *sql.DB
}
func getTemplates(path string) (*template.Template, error) {
templates := template.New("templates")
templateFolder, err := os.Open(path)
if err != nil {
return nil, err
}
defer templateFolder.Close()
templatePathsRaw, err := templateFolder.Readdir(-1)
if err != nil {
return nil, err
}
templatePaths := new([]string)
for _, pathInfo := range templatePathsRaw {
if !pathInfo.IsDir() {
fmt.Printf("%s%s \n", path, pathInfo.Name())
*templatePaths = append(*templatePaths, path+pathInfo.Name())
}
}
templates.ParseFiles(*templatePaths...)
return templates, nil
}
func NewPSQLLogHook(DB *sql.DB, tableName string) *PSQLLogHook {
return &PSQLLogHook{DB: DB, tableName: tableName}
}
func (psqlLogHook *PSQLLogHook) Fire(entry *log.Entry) error {
msg, ok := entry.Data["msg"]
if !ok {
return errors.New("Could not get entry.Data['msg'] in PSQLHook.Fire")
}
level, ok := entry.Data["level"]
if !ok {
return errors.New("Could not get entry.Data['level'] in PSQLHook.Fire")
}
var id string
err := psqlLogHook.DB.QueryRow("INSERT INTO log (msg, level) VALUES ($1, $2) RETURNING id", msg, level).Scan(&id)
if err != nil {
return err
}
if id == "" {
return errors.New("psqlLogHook didn't create a valid id")
}
return nil
}
func (psqlLogHook *PSQLLogHook) Levels() []log.Level {
return log.AllLevels
}
func (controller *Controller) Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
templateName := "index.html"
template := controller.templates.Lookup(templateName)
if template == nil {
errMsg := "template lookup on " + templateName + " returned nil"
log.WithFields(log.Fields{
"msg": errMsg,
"time": time.Now().Format(LOGGING_DATE_FORMAT),
"level": log.ErrorLevel.String(),
}).Errorln(errMsg)
}
template.Execute(w, nil)
}
func (controller *Controller) Math(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
templateName := "math.html"
template := controller.templates.Lookup(templateName)
if template == nil {
errMsg := "template lookup on " + templateName + " returned nil"
log.WithFields(log.Fields{
"msg": errMsg,
"time": time.Now().Format(LOGGING_DATE_FORMAT),
"level": log.ErrorLevel.String(),
}).Errorln(errMsg)
}
template.Execute(w, nil)
}
func (controller *Controller) NotFound(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
templateName := "404.html"
template := controller.templates.Lookup(templateName)
if template == nil {
errMsg := "template lookup on " + templateName + " returned nil"
log.WithFields(log.Fields{
"msg": errMsg,
"time": time.Now().Format(LOGGING_DATE_FORMAT),
"level": log.ErrorLevel.String(),
}).Errorln(errMsg)
}
template.Execute(w, nil)
}
func (controller *Controller) Static(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
fileName := params.ByName("filename")
if fileName == "" {
errMsg := "Static request did not contain a filename"
log.WithFields(log.Fields{
"msg": errMsg,
"time": time.Now().Format(LOGGING_DATE_FORMAT),
"level": log.ErrorLevel.String(),
}).Errorln(errMsg)
}
fileServer := http.FileServer(http.Dir(controller.staticDir))
log.Printf("Trying to load file: %s \n", fileName)
r.URL.Path = fileName
fileServer.ServeHTTP(w, r)
}
func main() {
log.SetOutput(os.Stdout)
dbUser := kingpin.Flag("dbuser", "Postgresql username").Default("denlillemand").String()
dbName := kingpin.Flag("dbname", "Postgresql dbname").Default("blog").String()
port := kingpin.Flag("port", "Webserver port").Default("3000").String()
staticDir := kingpin.Flag("static-dir", "Directory for static files").Default("$HOME/go/src/github.com/denlillemand/blog/dist/").String()
templateDir := kingpin.Flag("template-dir", "Directory for the golang templates").Default("$HOME/go/src/github.com/denlillemand/blog/templates/").String()
kingpin.Parse()
fmt.Printf("staticDir: %s templatesDir: %s \n", (*staticDir), (*templateDir))
staticDirExpanded := os.ExpandEnv((*staticDir))
templateDirExpanded := os.ExpandEnv((*templateDir))
connectionString := "user=" + *dbUser + " dbname=" + *dbName + " sslmode=disable"
db, err := sql.Open("postgres", connectionString)
if err != nil {
fmt.Printf("postgresql open failed! \n")
log.WithFields(log.Fields{
"msg": err.Error(),
"time": time.Now().Format(LOGGING_DATE_FORMAT),
"level": log.ErrorLevel.String(),
}).Errorln(err.Error())
}
defer db.Close()
err = db.Ping()
if err != nil {
fmt.Printf("postgresql ping failed!\n")
panic(err)
}
psqlLogHook := NewPSQLLogHook(db, "log")
log.AddHook(psqlLogHook)
templates, err := getTemplates(templateDirExpanded)
if err != nil {
fmt.Printf("get templates\n")
log.WithFields(log.Fields{
"msg": err.Error(),
"time": time.Now().Format(LOGGING_DATE_FORMAT),
"level": log.ErrorLevel.String(),
}).Errorln(err.Error())
}
controller := &Controller{templates: templates, staticDir: staticDirExpanded, templateDir: templateDirExpanded}
router := httprouter.New()
router.GET("/", controller.Index)
router.GET("/math", controller.Math)
router.GET("/404", controller.NotFound)
router.GET("/static/:filename", controller.Static)
infoMsg := "Started server at port:" + (*port)
log.WithFields(log.Fields{
"msg": infoMsg,
"level": log.InfoLevel.String(),
"time": time.Now().Format(LOGGING_DATE_FORMAT),
}).Infoln(infoMsg)
http.ListenAndServe(":"+(*port), router)
}