some updates related to json responses

pull/68/head
Henrique Dias 2016-03-06 15:56:53 +00:00
parent e33c79224f
commit ddcaccda0c
8 changed files with 88 additions and 76 deletions

File diff suppressed because one or more lines are too long

View File

@ -169,24 +169,26 @@ $(document).on('page:browse', function() {
request.send(JSON.stringify(content)); request.send(JSON.stringify(content));
request.onreadystatechange = function() { request.onreadystatechange = function() {
if (request.readyState == 4) { if (request.readyState == 4) {
if (request.status == 200) { var response = JSON.parse(request.responseText);
var data = JSON.parse(request.responseText); var type = "success";
var timeout = 5000;
notification({ if (request.status != 200) {
text: "File created successfully.", type = "error";
type: 'success', timeout = false;
timeout: 5000 }
});
notification({
text: response.message,
type: type,
timeout: timeout
});
if (request.status == 200) {
$.pjax({ $.pjax({
url: data.Location, url: data.Location,
container: '#content' container: '#content'
}) })
} else {
notification({
text: 'Something went wrong.',
type: 'error'
});
console.log(request.responseText);
} }
} }
} }
@ -353,4 +355,4 @@ $(document).on('page:browse', function() {
git.form.fadeOut(200); git.form.fadeOut(200);
return false; return false;
}); });
}); });

View File

@ -32,11 +32,17 @@ func DELETE(w http.ResponseWriter, r *http.Request, c *config.Config) (int, erro
// Check for errors // Check for errors
if err != nil { if err != nil {
return utils.RespondJSON(w, "Something went wrong.", 500, nil) return utils.RespondJSON(w, map[string]string{
"message": "Something went wrong.",
}, 500, nil)
} }
} else { } else {
return utils.RespondJSON(w, "File not found.", 404, nil) return utils.RespondJSON(w, map[string]string{
"message": "File not found.",
}, 404, nil)
} }
return utils.RespondJSON(w, message, 200, nil) return utils.RespondJSON(w, map[string]string{
"message": message,
}, 200, nil)
} }

View File

@ -36,11 +36,15 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
// Check if filename and archetype are specified in // Check if filename and archetype are specified in
// the request // the request
if _, ok := info["filename"]; !ok { if _, ok := info["filename"]; !ok {
return utils.RespondJSON(w, "Filename not specified.", 500, nil) return utils.RespondJSON(w, map[string]string{
"message": "Filename not specified.",
}, 500, nil)
} }
if _, ok := info["archetype"]; !ok { if _, ok := info["archetype"]; !ok {
return utils.RespondJSON(w, "Archtype not specified.", 500, nil) return utils.RespondJSON(w, map[string]string{
"message": "Archtype not specified.",
}, 500, nil)
} }
// Sanitize the file name path // Sanitize the file name path
@ -62,7 +66,9 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
} }
if err := utils.RunCommand(c.Hugo, args, c.Path); err != nil { if err := utils.RunCommand(c.Hugo, args, c.Path); err != nil {
return utils.RespondJSON(w, "Something went wrong.", 500, err) return utils.RespondJSON(w, map[string]string{
"message": "Something went wrong.",
}, 500, err)
} }
} else { } else {
var err error var err error
@ -77,22 +83,26 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
} }
if err != nil { if err != nil {
return utils.RespondJSON(w, "Something went wrong.", 500, err) return utils.RespondJSON(w, map[string]string{
"message": "Something went wrong.",
}, 500, err)
} }
} }
w.Header().Set("Content-Type", "application/json") return utils.RespondJSON(w, map[string]string{
w.WriteHeader(200) "location": url,
w.Write([]byte("{\"Location\": \"" + url + "\"}")) "message": "File created.",
return 0, nil }, 200, nil)
} }
func upload(w http.ResponseWriter, r *http.Request, c *config.Config) (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 {
return utils.RespondJSON(w, "Something went wrong.", 500, err) return utils.RespondJSON(w, map[string]string{
"message": "Something went wrong.",
}, 500, err)
} }
// For each file header in the multipart form // For each file header in the multipart form
@ -102,24 +112,29 @@ func upload(w http.ResponseWriter, r *http.Request, c *config.Config) (int, erro
// Open the first file // Open the first file
var infile multipart.File var infile multipart.File
if infile, err = hdr.Open(); nil != err { if infile, err = hdr.Open(); nil != err {
return utils.RespondJSON(w, "Something went wrong.", 500, err) return utils.RespondJSON(w, map[string]string{
"message": "Something went wrong.",
}, 500, err)
} }
// Create the file // Create the file
var outfile *os.File var outfile *os.File
if outfile, err = os.Create(c.Path + r.URL.Path + hdr.Filename); nil != err { if outfile, err = os.Create(c.Path + r.URL.Path + hdr.Filename); nil != err {
return utils.RespondJSON(w, "Something went wrong.", 500, err) return utils.RespondJSON(w, map[string]string{
"message": "Something went wrong.",
}, 500, err)
} }
// Copy the file content // Copy the file content
if _, err = io.Copy(outfile, infile); nil != err { if _, err = io.Copy(outfile, infile); nil != err {
return utils.RespondJSON(w, "Something went wrong.", 500, err) return utils.RespondJSON(w, map[string]string{
"message": "Something went wrong.",
}, 500, err)
} }
defer outfile.Close() defer outfile.Close()
} }
} }
return utils.RespondJSON(w, "", 200, nil) return utils.RespondJSON(w, nil, 200, nil)
return 0, nil
} }

View File

@ -31,7 +31,9 @@ func PUT(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
// Check if filename and archetype are specified in // Check if filename and archetype are specified in
// the request // the request
if _, ok := info["filename"]; !ok { if _, ok := info["filename"]; !ok {
return utils.RespondJSON(w, "Filename not specified.", 400, nil) return utils.RespondJSON(w, map[string]string{
"message": "Filename not specified.",
}, 400, nil)
} }
// Sanitize the file name path // Sanitize the file name path
@ -42,8 +44,12 @@ func PUT(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
// Renames the file/folder // Renames the file/folder
if err := os.Rename(old, new); err != nil { if err := os.Rename(old, new); err != nil {
return utils.RespondJSON(w, "Something went wrong.", 500, err) return utils.RespondJSON(w, map[string]string{
"message": "Something went wrong.",
}, 500, err)
} }
return utils.RespondJSON(w, "File renamed.", 200, nil) return utils.RespondJSON(w, map[string]string{
"message": "File renamed.",
}, 200, nil)
} }

View File

@ -8,14 +8,16 @@ import (
"strings" "strings"
"github.com/hacdias/caddy-hugo/config" "github.com/hacdias/caddy-hugo/config"
"github.com/hacdias/caddy-hugo/utils"
) )
// 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, c *config.Config) (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 {
jsonMessage(w, "Git is not installed on your computer.", 500) return utils.RespondJSON(w, map[string]string{
return 0, nil "message": "Git is not installed on your computer.",
}, 400, nil)
} }
// Get the JSON information sent using a buffer // Get the JSON information sent using a buffer
@ -28,8 +30,9 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
// Check if command was sent // Check if command was sent
if _, ok := info["command"]; !ok { if _, ok := info["command"]; !ok {
jsonMessage(w, "Command not specified.", 500) return utils.RespondJSON(w, map[string]string{
return 0, nil "message": "Command not specified.",
}, 400, nil)
} }
command := info["command"].(string) command := info["command"].(string)
@ -40,8 +43,9 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
} }
if len(args) == 0 { if len(args) == 0 {
jsonMessage(w, "Command not specified.", 500) return utils.RespondJSON(w, map[string]string{
return 0, nil "message": "Command not specified.",
}, 400, nil)
} }
cmd := exec.Command("git", args...) cmd := exec.Command("git", args...)
@ -49,25 +53,12 @@ func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
jsonMessage(w, err.Error(), 500) return utils.RespondJSON(w, map[string]string{
return 0, nil "message": err.Error(),
}, 500, err)
} }
jsonMessage(w, string(output), 200) return utils.RespondJSON(w, map[string]string{
return 0, nil "message": string(output),
} }, 200, nil)
type jsonMSG struct {
Message string `json:"message"`
}
func jsonMessage(w http.ResponseWriter, message string, code int) {
msg := &jsonMSG{
Message: message,
}
m, _ := json.Marshal(msg)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(m)
} }

View File

@ -1,6 +1,6 @@
//go:generate go get github.com/jteeuwen/go-bindata //go:generate go get github.com/jteeuwen/go-bindata
//go:generate go install github.com/jteeuwen/go-bindata/go-bindata //go:generate go install github.com/jteeuwen/go-bindata/go-bindata
//go:generate go-bindata -debug -pkg assets -o assets/assets.go templates/ assets/css/ assets/js/ assets/fonts/ //go:generate go-bindata -pkg assets -o assets/assets.go templates/ assets/css/ assets/js/ assets/fonts/
// Package hugo makes the bridge between the static website generator Hugo // Package hugo makes the bridge between the static website generator Hugo
// and the webserver Caddy, also providing an administrative user interface. // and the webserver Caddy, also providing an administrative user interface.

View File

@ -238,27 +238,19 @@ func SplitCapitalize(name string) string {
return name return name
} }
type jsonMSG struct { func RespondJSON(w http.ResponseWriter, message map[string]string, code int, err error) (int, error) {
Message string `json:"message"` msg, msgErr := json.Marshal(message)
}
func RespondJSON(w http.ResponseWriter, message string, code int, err error) (int, error) { if msgErr != nil {
msg := &jsonMSG{ return 500, msgErr
Message: message,
} }
m, err := json.Marshal(msg) if code == 500 && err != nil {
err = errors.New(message["message"])
if err != nil {
return 500, err
}
if code == 500 && err == nil {
err = errors.New(message)
} }
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code) w.WriteHeader(code)
w.Write(m) w.Write(msg)
return 0, err return 0, err
} }