package admin import ( "io/ioutil" "net/http" "net/url" "os" "path/filepath" "strings" "github.com/kirsle/blog/core/internal/render" "github.com/kirsle/blog/core/internal/responses" ) // FileTree holds information about files in the document roots. type FileTree struct { UserRoot bool // false = CoreRoot Files []render.Filepath } func editorHandler(w http.ResponseWriter, r *http.Request) { // Editing a page? file := strings.Trim(r.FormValue("file"), "/") if len(file) > 0 { var ( fp string fromCore = r.FormValue("from") == "core" saving = r.FormValue("action") == "save" deleting = r.FormValue("action") == "delete" body = []byte{} ) // Are they saving? if saving { fp = filepath.Join(*render.UserRoot, file) body = []byte(r.FormValue("body")) err := ioutil.WriteFile(fp, body, 0644) if err != nil { responses.Flash(w, r, "Error saving: %s", err) } else { responses.FlashAndRedirect(w, r, "/admin/editor?file="+url.QueryEscape(file), "Page saved successfully!") return } } else if deleting { fp = filepath.Join(*render.UserRoot, file) err := os.Remove(fp) if err != nil { responses.FlashAndRedirect(w, r, "/admin/editor", "Error deleting: %s", err) } else { responses.FlashAndRedirect(w, r, "/admin/editor", "Page deleted!") return } } else { // Where is the file from? if fromCore { fp = filepath.Join(*render.DocumentRoot, file) } else { fp = filepath.Join(*render.UserRoot, file) } // Check the file. If not found, check from the core root. f, err := os.Stat(fp) if os.IsNotExist(err) { fp = filepath.Join(*render.DocumentRoot, file) fromCore = true f, err = os.Stat(fp) } // If it exists, load it. if !os.IsNotExist(err) && !f.IsDir() { body, err = ioutil.ReadFile(fp) if err != nil { responses.Flash(w, r, "Error reading %s: %s", fp, err) } } // Default HTML boilerplate for .gohtml templates. if len(body) == 0 && strings.HasSuffix(fp, ".gohtml") { body = []byte("{{ define \"title\" }}Untitled Page{{ end }}\n" + "{{ define \"content\" }}\n