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