Last active
November 28, 2015 03:58
-
-
Save gebv/5d9e66564d72856fc8b1 to your computer and use it in GitHub Desktop.
helpful http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package core | |
import ( | |
"encoding/json" | |
"net/http" | |
"io/ioutil" | |
) | |
type ResponseSuccess struct { | |
Code string `json:"code"` | |
Data interface{} `json:"data"` | |
} | |
type ResponseError struct { | |
Code string `json:"error_code"` | |
Description string `json:"error_description"` | |
DevDescription string `json:"dev_description"` | |
} | |
func securityHandler(h http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
h.ServeHTTP(w, r) | |
return | |
} | |
} | |
func OutputErrorJSON(w http.ResponseWriter, code, message, devMessage string) error { | |
return OutputJSON(w, ResponseError{code, message, devMessage}) | |
} | |
func OutputJSON(w http.ResponseWriter, data interface{}) error { | |
w.Header().Set("Content-Type", "application/json") | |
encoder := json.NewEncoder(w) | |
err := encoder.Encode(data) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
func InputBytes(r *http.Request) ([]byte, error) { | |
if err := r.ParseForm(); err != nil { | |
return []byte{}, ErrInvalidData | |
} | |
return ioutil.ReadAll(r.Body) | |
} | |
func InputJSON(w http.ResponseWriter, r *http.Request, data interface{}) error { | |
if err := r.ParseForm(); err != nil { | |
w.WriteHeader(400) | |
OutputJSON(w, &ResponseError{CodeInvalidData, "", "Ivalid data"}) | |
return ErrInvalidData | |
} | |
decoder := json.NewDecoder(r.Body) | |
err := decoder.Decode(data) | |
if err != nil { | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment