Replace json config with flags and fix various bugs

This commit is contained in:
Nise Void 2017-06-02 21:41:14 +02:00
parent 044cb3667c
commit ea9d6176d2
1 changed files with 17 additions and 34 deletions

51
main.go
View File

@ -1,7 +1,7 @@
package main package main
import ( import (
"encoding/json" "flag"
"html/template" "html/template"
"io/ioutil" "io/ioutil"
"log" "log"
@ -15,40 +15,28 @@ import (
) )
func main() { func main() {
if err := loadConfig(); err != nil { loadConfig()
log.Fatal(`Failed to load config. ` + err.Error())
}
if err := updateTemplate(); err != nil { if err := updateTemplate(); err != nil {
log.Fatal(`Failed to load template. ` + err.Error()) log.Fatal(`Failed to load template. (` + err.Error() + `)`)
} }
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(config.Port), http.HandlerFunc(serveRequest))) log.Fatal(http.ListenAndServe(":"+strconv.Itoa(config.Port), http.HandlerFunc(serveRequest)))
} }
var config struct { var config struct {
Port int `json:"port"` Port int
Template string `json:"template"` Template string
Pages string
Static string
} }
func loadConfig() error { func loadConfig() {
f, err := os.Open(`config.json`) flag.IntVar(&config.Port, `port`, 80, `The port mdsite will listen on`)
if err != nil && !os.IsNotExist(err) { flag.StringVar(&config.Template, `template`, `template.html`, `The template used by mdsite`)
return err flag.StringVar(&config.Pages, `pages`, `pages`, `The OS path used when searching a page`)
} flag.StringVar(&config.Static, `static`, `static`, `The OS path used for static resource`)
flag.Parse()
// Set defaults
config.Port = 80
config.Template = `template.html`
if err != nil {
return
}
err = json.NewDecoder(f).Decode(&config)
if err != nil {
return err
}
} }
var t *template.Template var t *template.Template
@ -64,23 +52,18 @@ func updateTemplate() error {
func serveRequest(w http.ResponseWriter, r *http.Request) { func serveRequest(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, `/static/`) { if strings.HasPrefix(r.URL.Path, `/static/`) {
p, _ := os.Getwd() path := path.Join(config.Static, path.Clean(strings.TrimPrefix(r.URL.Path, `/static/`)))
p = path.Join(p, r.URL.Path) http.ServeFile(w, r, path)
http.ServeFile(w, r, p)
return return
} }
servePage(w, r) servePage(w, r)
} }
func servePage(w http.ResponseWriter, r *http.Request) { func servePage(w http.ResponseWriter, r *http.Request) {
p := `pages` + path.Clean(r.URL.Path) p := path.Join(config.Pages, path.Clean(r.URL.Path))
s, err := os.Stat(p) s, err := os.Stat(p)
if err != nil { if err == nil && s.IsDir() {
w.WriteHeader(404)
return
}
if s.IsDir() {
if p[len(p)-1] != '/' { if p[len(p)-1] != '/' {
p += `/` p += `/`
} }