2015-09-12 19:02:26 +00:00
|
|
|
package edit
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io/ioutil"
|
2015-09-14 09:46:31 +00:00
|
|
|
"log"
|
2015-09-12 19:02:26 +00:00
|
|
|
"net/http"
|
|
|
|
"os"
|
2015-09-13 20:10:54 +00:00
|
|
|
"strings"
|
2015-09-13 11:14:18 +00:00
|
|
|
|
2015-09-14 21:03:09 +00:00
|
|
|
"github.com/hacdias/caddy-hugo/frontmatter"
|
2015-09-13 11:14:18 +00:00
|
|
|
"github.com/hacdias/caddy-hugo/page"
|
2015-09-13 19:37:20 +00:00
|
|
|
"github.com/spf13/hugo/commands"
|
2015-09-14 21:03:09 +00:00
|
|
|
"github.com/spf13/hugo/parser"
|
2015-09-12 19:02:26 +00:00
|
|
|
)
|
|
|
|
|
2015-09-14 21:03:09 +00:00
|
|
|
type information struct {
|
|
|
|
Name string
|
|
|
|
Content string
|
|
|
|
FrontMatter interface{}
|
2015-09-12 19:02:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Execute sth
|
2015-09-13 20:10:54 +00:00
|
|
|
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-13 20:10:54 +00:00
|
|
|
|
2015-09-12 19:02:26 +00:00
|
|
|
if r.Method == "POST" {
|
2015-09-13 19:37:20 +00:00
|
|
|
r.ParseForm()
|
|
|
|
err := ioutil.WriteFile(filename, []byte(r.Form["content"][0]), 0666)
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
commands.Execute()
|
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
|
|
|
|
}
|
|
|
|
|
2015-09-14 21:03:09 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2015-09-14 21:03:09 +00:00
|
|
|
file, err := parser.ReadFrom(reader)
|
|
|
|
|
|
|
|
inf := new(information)
|
|
|
|
inf.Content = 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
|
|
|
|
2015-09-13 11:28:26 +00:00
|
|
|
page := new(page.Page)
|
2015-09-13 11:14:18 +00:00
|
|
|
page.Title = "Edit"
|
2015-09-13 11:28:26 +00:00
|
|
|
page.Body = inf
|
2015-09-14 21:03:09 +00:00
|
|
|
return page.Render(w, r, "edit", "frontmatter")
|
2015-09-12 19:02:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return 200, nil
|
|
|
|
}
|