filebrowser/settings/settings.go

97 lines
1.7 KiB
Go
Raw Normal View History

2015-09-13 21:48:52 +00:00
package settings
import (
2015-09-14 17:18:26 +00:00
"bytes"
"encoding/json"
2015-09-13 21:48:52 +00:00
"io/ioutil"
2015-09-14 13:42:48 +00:00
"log"
2015-09-13 21:48:52 +00:00
"net/http"
"os"
2015-09-14 13:42:48 +00:00
"github.com/hacdias/caddy-hugo/frontmatter"
2015-09-13 21:48:52 +00:00
"github.com/hacdias/caddy-hugo/page"
2015-09-14 17:18:26 +00:00
"github.com/spf13/hugo/commands"
2015-09-13 21:48:52 +00:00
)
2015-09-14 17:18:26 +00:00
type test struct {
Test string
}
2015-09-13 21:48:52 +00:00
// Execute the page
func Execute(w http.ResponseWriter, r *http.Request) (int, error) {
2015-09-14 17:18:26 +00:00
language := getConfigFrontMatter()
2015-09-13 21:48:52 +00:00
2015-09-14 17:18:26 +00:00
if language == "" {
log.Print("Configuration frontmatter can't be defined")
return 500, nil
}
2015-09-13 21:48:52 +00:00
2015-09-14 17:18:26 +00:00
if r.Method == "POST" {
err := os.Remove("config." + language)
if err != nil {
log.Print(err)
2015-09-13 21:48:52 +00:00
return 500, nil
}
2015-09-14 17:18:26 +00:00
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
raw := buf.Bytes()
content := new(bytes.Buffer)
json.Indent(content, raw, "", " ")
err = ioutil.WriteFile("config.json", content.Bytes(), 0666)
if err != nil {
log.Print(err)
return 500, err
}
2015-09-14 17:41:49 +00:00
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{}"))
2015-09-14 21:36:15 +00:00
if r.Header.Get("X-Save-Mode") == "publish" {
go commands.Execute()
}
2015-09-14 17:18:26 +00:00
} else {
2015-09-14 13:42:48 +00:00
content, err := ioutil.ReadFile("config." + language)
2015-09-13 21:48:52 +00:00
if err != nil {
2015-09-14 13:42:48 +00:00
log.Print(err)
2015-09-13 21:48:52 +00:00
return 500, err
}
f, err := frontmatter.Pretty(content)
2015-09-14 09:46:31 +00:00
2015-09-14 13:42:48 +00:00
if err != nil {
log.Print(err)
return 500, err
}
2015-09-14 09:46:31 +00:00
2015-09-13 21:48:52 +00:00
page := new(page.Page)
2015-09-14 09:46:31 +00:00
page.Title = "Settings"
2015-09-14 13:42:48 +00:00
page.Body = f
2015-09-14 17:18:26 +00:00
return page.Render(w, r, "settings", "frontmatter")
2015-09-13 21:48:52 +00:00
}
return 200, nil
}
func getConfigFrontMatter() string {
var frontmatter string
if _, err := os.Stat("config.yaml"); err == nil {
frontmatter = "yaml"
}
if _, err := os.Stat("config.json"); err == nil {
frontmatter = "json"
}
if _, err := os.Stat("config.toml"); err == nil {
frontmatter = "toml"
}
return frontmatter
}