filebrowser/edit/edit.go

101 lines
2.1 KiB
Go
Raw Normal View History

2015-09-12 19:02:26 +00:00
package edit
import (
2015-09-14 21:36:15 +00:00
"bytes"
"encoding/json"
2015-09-12 19:02:26 +00:00
"io/ioutil"
2015-09-14 09:46:31 +00:00
"log"
2015-09-12 19:02:26 +00:00
"net/http"
"os"
"strings"
2015-09-13 11:14:18 +00:00
"github.com/hacdias/caddy-hugo/frontmatter"
2015-09-13 11:14:18 +00:00
"github.com/hacdias/caddy-hugo/page"
"github.com/spf13/hugo/parser"
2015-09-12 19:02:26 +00:00
)
type information struct {
Name string
Content string
FrontMatter interface{}
2015-09-12 19:02:26 +00:00
}
// Execute sth
func Execute(w http.ResponseWriter, r *http.Request) (int, error) {
2015-09-13 20:45:40 +00:00
filename := strings.Replace(r.URL.Path, "/admin/edit/", "", 1)
2015-09-12 19:02:26 +00:00
if r.Method == "POST" {
2015-09-14 21:36:15 +00:00
// Get the JSON information sent using a buffer
rawBuffer := new(bytes.Buffer)
rawBuffer.ReadFrom(r.Body)
// Creates the raw file "map" using the JSON
var rawFile map[string]interface{}
json.Unmarshal(rawBuffer.Bytes(), &rawFile)
// The main content of the file
mainContent := rawFile["content"].(string)
2015-09-15 18:26:18 +00:00
mainContent = "\n\n" + strings.TrimSpace(mainContent)
2015-09-14 21:36:15 +00:00
// Removes the main content from the rest of the frontmatter
delete(rawFile, "content")
// Converts the frontmatter in JSON
jsonFrontmatter, err := json.Marshal(rawFile)
if err != nil {
log.Print(err)
return 500, err
}
// Indents the json
frontMatterBuffer := new(bytes.Buffer)
json.Indent(frontMatterBuffer, jsonFrontmatter, "", " ")
// Generates the final file
file := new(bytes.Buffer)
file.Write(frontMatterBuffer.Bytes())
file.Write([]byte(mainContent))
err = ioutil.WriteFile(filename, file.Bytes(), 0666)
2015-09-13 19:37:20 +00:00
if err != nil {
2015-09-14 09:46:31 +00:00
log.Print(err)
2015-09-13 19:37:20 +00:00
return 500, err
}
2015-09-14 21:36:15 +00:00
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{}"))
2015-09-12 19:02:26 +00:00
} else {
2015-09-13 19:37:20 +00:00
if _, err := os.Stat(filename); os.IsNotExist(err) {
2015-09-14 09:46:31 +00:00
log.Print(err)
2015-09-12 19:02:26 +00:00
return 404, nil
}
reader, err := os.Open(filename)
2015-09-13 11:14:18 +00:00
if err != nil {
2015-09-14 09:46:31 +00:00
log.Print(err)
2015-09-13 11:14:18 +00:00
return 500, err
}
file, err := parser.ReadFrom(reader)
inf := new(information)
2015-09-15 18:26:18 +00:00
inf.Content = strings.TrimSpace(string(file.Content()))
inf.FrontMatter, err = frontmatter.Pretty(file.FrontMatter())
if err != nil {
log.Print(err)
return 500, err
}
2015-09-12 21:18:29 +00:00
page := new(page.Page)
2015-09-17 16:41:31 +00:00
page.Name = "Edit"
page.Body = inf
return page.Render(w, r, "edit", "frontmatter")
2015-09-12 19:02:26 +00:00
}
return 200, nil
}