Mercurial > gemma
diff pkg/controllers/json.go @ 1693:cdc8933949f2
Controllers: Resolved the remaining golint issues with this package.
author | Sascha L. Teichmann <teichmann@intevation.de> |
---|---|
date | Thu, 03 Jan 2019 17:46:59 +0100 |
parents | 8f5a5c86f2a9 |
children | 09f9ae3d0526 |
line wrap: on
line diff
--- a/pkg/controllers/json.go Mon Dec 31 11:13:49 2018 +0100 +++ b/pkg/controllers/json.go Thu Jan 03 17:46:59 2019 +0100 @@ -26,29 +26,55 @@ "gemma.intevation.de/gemma/pkg/auth" ) +// JSONResult defines the return type of JSONHandler handler function. type JSONResult struct { - Code int + // Code is the HTTP status code to be set which defaults to http.StatusOK (200). + Code int + // Result is serialized to JSON. + // If the type is an io.Reader its copied through. Result interface{} } +// JSONDefaultLimit is default size limit in bytes of an accepted +// input document. const JSONDefaultLimit = 2048 +// JSONHandler implements a middleware to ease the handing JSON input +// streams and return JSON documents as output. type JSONHandler struct { - Input func() interface{} - Handle func(interface{}, *http.Request, *sql.Conn) (JSONResult, error) + // Input (if not nil) is called to fill a data structure + // returned by this function. + Input func() interface{} + // Handle is called to handle the incoming HTTP request. + // in is the data structure returned by Input. Its nil if Input is nil. + // req is the incoming HTTP request. + // conn is the impersonated connection to the database. + Handle func(in interface{}, rep *http.Request, conn *sql.Conn) (JSONResult, error) + // NoConn if set to true no database connection is established and + // the conn parameter of the Handle call is nil. NoConn bool - Limit int64 + // Limit overides the default size of accepted input documents. + // Set to a negative value to allow an arbitrary size. + // Handle with care! + Limit int64 } +// JSONError is an error if returned by the JSONHandler.Handle function +// which ends up encoded as a JSON document. type JSONError struct { - Code int + // Code is the HTTP status code of the result defaults + // to http.StatusInternalServerError if not set. + Code int + // The message of the error. Message string } +// Error implements the error interface. func (je JSONError) Error() string { return fmt.Sprintf("%d: %s", je.Code, je.Message) } +// ServeHTTP makes the JSONHandler a middleware. func (j *JSONHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { var input interface{} @@ -147,6 +173,8 @@ } } +// SendJSON sends data JSON encoded to the response writer +// with a given HTTP status code. func SendJSON(rw http.ResponseWriter, code int, data interface{}) { rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(code)