autojson

package module
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 14, 2018 License: MIT Imports: 6 Imported by: 0

README

Go Report Card Godoc

This library will generate an HTTP HandlerFunc that takes JSON as input, and returns JSON as output. Pass it an object, and a method name of that object as a string. You can have various combinations of arguments and return values to control behavior, depending on the value types. All are optional.

Method Argument Types

An argument of type context.Context, http.ResponseWriter, http.Request will be copied from the source request.

Any remaining argument will be populated with data by encoding/json from the request body.

Method Return Types

If you return a value of type error, it will be used to generate an HTTP 500 with a message if non-nil.

If you return an int, it will be used as the HTTP status code, overriding any code (including the 500 from an error).

If you return any other value, it will be marshalled by encoding/json and returned to the client.

Examples

type service int

func (_ service) Simple() string {
    // This will return an HTTP 200 with a JSON encoded string "Hi there"
    return "Hi there"
}

func (_ service) SimpleWithStatus() (string, int) {
    // Same but for HTTP 201
    return "greeeeetings", 201
}

func (_ service) IntegerWithStatus() (int, int) {
    // The first integer will be the HTTP code.
    // So this will return an HTTP 418 I'm a teapot with a JSON encoded number 666
    return 418, 666
}

type Resp struct {
    // A more complex JSON data structure
    Things []string
}
func (_ service) CustomHeader(w http.ResponseWriter) Resp {
    w.Header().Set("X-Stuff", "fruits")
    return Resp{Things: []string{"apple", "banana", "cherry"}}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewHandler

func NewHandler(service interface{}, methodName string) http.HandlerFunc

NewHandler uses reflection to generate an http.HandlerFunc from a service and method name

Types

type ErrorResponse added in v0.0.4

type ErrorResponse struct {
	Error string `json:"error"`
}

ErrorResponse will be returned if your handler has a return value of type error, with the stringified error populated.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL