remove dangerous global variables

pull/78/head
Henrique Dias 2016-06-16 17:01:41 +01:00
parent 48878cc3b5
commit af2785e510
11 changed files with 66 additions and 82 deletions

View File

@ -1,15 +1,12 @@
package browse package browse
import ( import (
"errors"
"net/http" "net/http"
"strings" "strings"
"github.com/hacdias/caddy-hugo/config" "github.com/hacdias/caddy-hugo/config"
) )
var conf *config.Config
type response struct { type response struct {
Message string `json:"message"` Message string `json:"message"`
Location string `json:"location"` Location string `json:"location"`
@ -19,20 +16,18 @@ type response struct {
// from Caddy. It handles the requests for DELETE, POST, GET and PUT related to // from Caddy. It handles the requests for DELETE, POST, GET and PUT related to
// /browse interface. // /browse interface.
func ServeHTTP(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) { func ServeHTTP(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
conf = c
// Removes the page main path from the URL
r.URL.Path = strings.Replace(r.URL.Path, c.Admin+"/browse", "", 1) r.URL.Path = strings.Replace(r.URL.Path, c.Admin+"/browse", "", 1)
switch r.Method { switch r.Method {
case "DELETE": case "DELETE":
return DELETE(w, r) return DELETE(w, r, c)
case "POST": case "POST":
return POST(w, r, c) return POST(w, r, c)
case "GET": case "GET":
return GET(w, r) return GET(w, r, c)
case "PUT": case "PUT":
return PUT(w, r) return PUT(w, r, c)
default: default:
return http.StatusMethodNotAllowed, errors.New("Invalid method.") return http.StatusNotImplemented, nil
} }
} }

View File

@ -5,16 +5,17 @@ import (
"os" "os"
"strings" "strings"
"github.com/hacdias/caddy-hugo/config"
s "github.com/hacdias/caddy-hugo/tools/server" s "github.com/hacdias/caddy-hugo/tools/server"
) )
// DELETE handles the delete requests on browse pages // DELETE handles the delete requests on browse pages
func DELETE(w http.ResponseWriter, r *http.Request) (int, error) { func DELETE(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
// Remove both beginning and trailing slashes // Remove both beginning and trailing slashes
path := r.URL.Path path := r.URL.Path
path = strings.TrimPrefix(path, "/") path = strings.TrimPrefix(path, "/")
path = strings.TrimSuffix(path, "/") path = strings.TrimSuffix(path, "/")
path = conf.Path + path path = c.Path + path
message := "File deleted." message := "File deleted."

View File

@ -4,6 +4,7 @@ import (
"net/http" "net/http"
"text/template" "text/template"
"github.com/hacdias/caddy-hugo/config"
"github.com/hacdias/caddy-hugo/tools/templates" "github.com/hacdias/caddy-hugo/tools/templates"
"github.com/hacdias/caddy-hugo/tools/variables" "github.com/hacdias/caddy-hugo/tools/variables"
"github.com/mholt/caddy/caddyhttp/browse" "github.com/mholt/caddy/caddyhttp/browse"
@ -12,7 +13,7 @@ import (
// GET handles the GET method on browse page and shows the files listing Using // GET handles the GET method on browse page and shows the files listing Using
// the Browse Caddy middleware. // the Browse Caddy middleware.
func GET(w http.ResponseWriter, r *http.Request) (int, error) { func GET(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
functions := template.FuncMap{ functions := template.FuncMap{
"CanBeEdited": templates.CanBeEdited, "CanBeEdited": templates.CanBeEdited,
"Defined": variables.Defined, "Defined": variables.Defined,
@ -32,8 +33,8 @@ func GET(w http.ResponseWriter, r *http.Request) (int, error) {
Configs: []browse.Config{ Configs: []browse.Config{
{ {
PathScope: "/", PathScope: "/",
Root: http.Dir(conf.Path), Root: http.Dir(c.Path),
Variables: conf, Variables: c,
Template: tpl, Template: tpl,
}, },
}, },

View File

@ -23,7 +23,7 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
// If it's the upload of a file // If it's the upload of a file
if r.Header.Get("X-Upload") == "true" { if r.Header.Get("X-Upload") == "true" {
return upload(w, r) return upload(w, r, c)
} }
// Get the JSON information sent using a buffer // Get the JSON information sent using a buffer
@ -49,12 +49,12 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
filename = strings.TrimPrefix(filename, "/") filename = strings.TrimPrefix(filename, "/")
filename = strings.TrimSuffix(filename, "/") filename = strings.TrimSuffix(filename, "/")
url := c.Admin + "/edit/" + r.URL.Path + filename url := c.Admin + "/edit/" + r.URL.Path + filename
filename = conf.Path + r.URL.Path + filename filename = c.Path + r.URL.Path + filename
if strings.HasPrefix(filename, conf.Path+"content/") && if strings.HasPrefix(filename, c.Path+"content/") &&
(strings.HasSuffix(filename, ".md") || strings.HasSuffix(filename, ".markdown")) { (strings.HasSuffix(filename, ".md") || strings.HasSuffix(filename, ".markdown")) {
filename = strings.Replace(filename, conf.Path+"content/", "", 1) filename = strings.Replace(filename, c.Path+"content/", "", 1)
args := []string{"new", filename} args := []string{"new", filename}
archetype := info["archetype"].(string) archetype := info["archetype"].(string)
@ -62,7 +62,7 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
args = append(args, "--kind", archetype) args = append(args, "--kind", archetype)
} }
if err := commands.Run(conf.Hugo, args, conf.Path); err != nil { if err := commands.Run(c.Hugo, args, c.Path); err != nil {
return s.RespondJSON(w, &response{"Something went wrong.", ""}, http.StatusInternalServerError, err) return s.RespondJSON(w, &response{"Something went wrong.", ""}, http.StatusInternalServerError, err)
} }
} else { } else {
@ -86,7 +86,7 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
return s.RespondJSON(w, &response{"File created!", url}, http.StatusOK, nil) return s.RespondJSON(w, &response{"File created!", url}, http.StatusOK, nil)
} }
func upload(w http.ResponseWriter, r *http.Request) (int, error) { func upload(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
// Parse the multipart form in the request // Parse the multipart form in the request
err := r.ParseMultipartForm(100000) err := r.ParseMultipartForm(100000)
if err != nil { if err != nil {
@ -105,7 +105,7 @@ func upload(w http.ResponseWriter, r *http.Request) (int, error) {
// Create the file // Create the file
var outfile *os.File var outfile *os.File
if outfile, err = os.Create(conf.Path + r.URL.Path + hdr.Filename); nil != err { if outfile, err = os.Create(c.Path + r.URL.Path + hdr.Filename); nil != err {
return s.RespondJSON(w, &response{"Something went wrong.", ""}, http.StatusInternalServerError, err) return s.RespondJSON(w, &response{"Something went wrong.", ""}, http.StatusInternalServerError, err)
} }

View File

@ -7,17 +7,18 @@ import (
"os" "os"
"strings" "strings"
"github.com/hacdias/caddy-hugo/config"
"github.com/hacdias/caddy-hugo/tools/server" "github.com/hacdias/caddy-hugo/tools/server"
) )
// PUT handles the HTTP PUT request for all /{admin}/browse related requests. // PUT handles the HTTP PUT request for all /{admin}/browse related requests.
// Renames a file and/or a folder. // Renames a file and/or a folder.
func PUT(w http.ResponseWriter, r *http.Request) (int, error) { func PUT(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
// Remove both beginning and trailing slashes // Remove both beginning and trailing slashes
old := r.URL.Path old := r.URL.Path
old = strings.TrimPrefix(old, "/") old = strings.TrimPrefix(old, "/")
old = strings.TrimSuffix(old, "/") old = strings.TrimSuffix(old, "/")
old = conf.Path + old old = c.Path + old
// Get the JSON information sent using a buffer // Get the JSON information sent using a buffer
buffer := new(bytes.Buffer) buffer := new(bytes.Buffer)
@ -37,7 +38,7 @@ func PUT(w http.ResponseWriter, r *http.Request) (int, error) {
new := info["filename"].(string) new := info["filename"].(string)
new = strings.TrimPrefix(new, "/") new = strings.TrimPrefix(new, "/")
new = strings.TrimSuffix(new, "/") new = strings.TrimSuffix(new, "/")
new = conf.Path + new new = c.Path + new
// Renames the file/folder // Renames the file/folder
if err := os.Rename(old, new); err != nil { if err := os.Rename(old, new); err != nil {

View File

@ -1,30 +1,23 @@
package editor package editor
import ( import (
"errors"
"net/http" "net/http"
"strings" "strings"
"github.com/hacdias/caddy-hugo/config" "github.com/hacdias/caddy-hugo/config"
) )
var (
filename string
conf *config.Config
)
// ServeHTTP serves the editor page // ServeHTTP serves the editor page
func ServeHTTP(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) { func ServeHTTP(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
conf = c filename := strings.Replace(r.URL.Path, c.Admin+"/edit/", "", 1)
filename = strings.Replace(r.URL.Path, c.Admin+"/edit/", "", 1)
filename = c.Path + filename filename = c.Path + filename
switch r.Method { switch r.Method {
case "POST": case http.MethodPost:
return POST(w, r) return POST(w, r, c, filename)
case "GET": case http.MethodGet:
return GET(w, r) return GET(w, r, c, filename)
default: default:
return http.StatusMethodNotAllowed, errors.New("Invalid method.") return http.StatusNotImplemented, nil
} }
} }

View File

@ -28,7 +28,7 @@ type editor struct {
} }
// GET handles the GET method on editor page // GET handles the GET method on editor page
func GET(w http.ResponseWriter, r *http.Request) (int, error) { func GET(w http.ResponseWriter, r *http.Request, c *config.Config, filename string) (int, error) {
// Check if the file format is supported. If not, send a "Not Acceptable" // Check if the file format is supported. If not, send a "Not Acceptable"
// header and an error // header and an error
if !templates.CanBeEdited(filename) { if !templates.CanBeEdited(filename) {
@ -55,8 +55,8 @@ func GET(w http.ResponseWriter, r *http.Request) (int, error) {
// Create a new editor variable and set the extension // Create a new editor variable and set the extension
page := new(editor) page := new(editor)
page.Mode = strings.TrimPrefix(filepath.Ext(filename), ".") page.Mode = strings.TrimPrefix(filepath.Ext(filename), ".")
page.Name = strings.Replace(filename, conf.Path, "", 1) page.Name = strings.Replace(filename, c.Path, "", 1)
page.Config = conf page.Config = c
page.IsPost = false page.IsPost = false
// Sanitize the extension // Sanitize the extension

View File

@ -11,6 +11,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/hacdias/caddy-hugo/config"
"github.com/hacdias/caddy-hugo/tools/hugo" "github.com/hacdias/caddy-hugo/tools/hugo"
"github.com/hacdias/caddy-hugo/tools/server" "github.com/hacdias/caddy-hugo/tools/server"
"github.com/robfig/cron" "github.com/robfig/cron"
@ -30,7 +31,7 @@ type response struct {
} }
// POST handles the POST method on editor page // POST handles the POST method on editor page
func POST(w http.ResponseWriter, r *http.Request) (int, error) { func POST(w http.ResponseWriter, r *http.Request, c *config.Config, filename string) (int, error) {
var data info var data info
// Get the JSON information sent using a buffer // Get the JSON information sent using a buffer
@ -50,7 +51,7 @@ func POST(w http.ResponseWriter, r *http.Request) (int, error) {
switch data.ContentType { switch data.ContentType {
case "frontmatter-only": case "frontmatter-only":
file, code, err = parseFrontMatterOnlyFile(data) file, code, err = parseFrontMatterOnlyFile(data, filename)
if err != nil { if err != nil {
return server.RespondJSON(w, &response{err.Error()}, code, err) return server.RespondJSON(w, &response{err.Error()}, code, err)
} }
@ -61,7 +62,7 @@ func POST(w http.ResponseWriter, r *http.Request) (int, error) {
file = []byte(mainContent) file = []byte(mainContent)
case "complete": case "complete":
file, code, err = parseCompleteFile(data) file, code, err = parseCompleteFile(data, filename, c)
if err != nil { if err != nil {
return server.RespondJSON(w, &response{err.Error()}, code, err) return server.RespondJSON(w, &response{err.Error()}, code, err)
} }
@ -77,13 +78,13 @@ func POST(w http.ResponseWriter, r *http.Request) (int, error) {
} }
if data.Regenerate { if data.Regenerate {
go hugo.Run(conf, false) go hugo.Run(c, false)
} }
return server.RespondJSON(w, nil, http.StatusOK, nil) return server.RespondJSON(w, nil, http.StatusOK, nil)
} }
func parseFrontMatterOnlyFile(data info) ([]byte, int, error) { func parseFrontMatterOnlyFile(data info, filename string) ([]byte, int, error) {
frontmatter := strings.TrimPrefix(filepath.Ext(filename), ".") frontmatter := strings.TrimPrefix(filepath.Ext(filename), ".")
var mark rune var mark rune
@ -121,7 +122,7 @@ func parseFrontMatterOnlyFile(data info) ([]byte, int, error) {
return f, http.StatusOK, nil return f, http.StatusOK, nil
} }
func parseCompleteFile(data info) ([]byte, int, error) { func parseCompleteFile(data info, filename string, c *config.Config) ([]byte, int, error) {
// The main content of the file // The main content of the file
mainContent := data.Content["content"].(string) mainContent := data.Content["content"].(string)
mainContent = "\n\n" + strings.TrimSpace(mainContent) + "\n" mainContent = "\n\n" + strings.TrimSpace(mainContent) + "\n"
@ -164,7 +165,7 @@ func parseCompleteFile(data info) ([]byte, int, error) {
return return
} }
go hugo.Run(conf, false) go hugo.Run(c, false)
}) })
scheduler.Start() scheduler.Start()
} }

View File

@ -26,27 +26,26 @@ func ServeHTTP(w http.ResponseWriter, r *http.Request, code int, err error) (int
page.Message = err.Error() page.Message = err.Error()
} }
switch r.Method { if r.Method != http.MethodGet {
case "GET":
functions := template.FuncMap{
"Defined": variables.Defined,
}
var tpl *template.Template
tpl, err = templates.Get(r, functions, "error")
if err != nil {
return http.StatusInternalServerError, err
}
err = tpl.Execute(w, page)
if err != nil {
return http.StatusInternalServerError, err
}
return 0, page.err
default:
return server.RespondJSON(w, page, code, err) return server.RespondJSON(w, page, code, err)
} }
functions := template.FuncMap{
"Defined": variables.Defined,
}
var tpl *template.Template
tpl, err = templates.Get(r, functions, "error")
if err != nil {
return http.StatusInternalServerError, err
}
err = tpl.Execute(w, page)
if err != nil {
return http.StatusInternalServerError, err
}
return 0, page.err
} }

View File

@ -1,24 +1,16 @@
package git package git
import ( import (
"errors"
"net/http" "net/http"
"github.com/hacdias/caddy-hugo/config" "github.com/hacdias/caddy-hugo/config"
) )
var (
conf *config.Config
)
// ServeHTTP is used to serve the content of GIT API. // ServeHTTP is used to serve the content of GIT API.
func ServeHTTP(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) { func ServeHTTP(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
conf = c if r.Method != http.MethodPost {
return http.StatusNotImplemented, nil
switch r.Method {
case "POST":
return POST(w, r)
default:
return http.StatusMethodNotAllowed, errors.New("Invalid method.")
} }
return POST(w, r, c)
} }

View File

@ -7,6 +7,7 @@ import (
"os/exec" "os/exec"
"strings" "strings"
"github.com/hacdias/caddy-hugo/config"
s "github.com/hacdias/caddy-hugo/tools/server" s "github.com/hacdias/caddy-hugo/tools/server"
) )
@ -15,7 +16,7 @@ type postError struct {
} }
// POST handles the POST method on GIT page which is only an API. // POST handles the POST method on GIT page which is only an API.
func POST(w http.ResponseWriter, r *http.Request) (int, error) { func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
// Check if git is installed on the computer // Check if git is installed on the computer
if _, err := exec.LookPath("git"); err != nil { if _, err := exec.LookPath("git"); err != nil {
return s.RespondJSON(w, &postError{"Git is not installed on your computer."}, 400, nil) return s.RespondJSON(w, &postError{"Git is not installed on your computer."}, 400, nil)
@ -46,7 +47,7 @@ func POST(w http.ResponseWriter, r *http.Request) (int, error) {
} }
cmd := exec.Command("git", args...) cmd := exec.Command("git", args...)
cmd.Dir = conf.Path cmd.Dir = c.Path
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {