margo

package module
v0.0.0-...-27d39a1 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2018 License: MIT Imports: 7 Imported by: 1

README

margo

GoDoc Go Report Card

A tiny framework on top of gin.

Motivation

gin is an amazing framework, but when writing handler functions and middleware it is easy to get confused keeping track where headers are set and data is written to the response.

margo solves this by having its handler functions return an object implementing the Response interface, whose Send method is responsible for transmitting data to the client.

Example usage

type errorResponse struct {
    err error
}

// satisfies margo.Response
func (r *errorResponse) Send(context *gin.Context) error {
    context.String(http.StatusInternalServerError, "an internal server error occurred: %s", r.err.Error())
    return nil
}

func newErrorResponse(err error) margo.Response {
    return &errorResponse{
        err: err,
    }
}

func main() {
    // create new Application instance
    app := margo.NewApplication()

    // create endpoint handling the index route
    endpoint := margo.GET("/", func(context *gin.Context) margo.Response {
        // handle the request however you wish, for example
        // parse some request parameters
        params, err := parseQueryParams(context)
        if err != nil {
            // handle the error however you like,
            // for example by returning a generic error response
            // which implements margo.Response
            return newErrorResponse(err)
        }

        // do something with the retrieved params,
        // for example output them as json using
        // the builtin JSON function
        return margo.JSON(http.StatusOK, params)
    })
    app.Endpoint(endpoint) // register endpoint with Application

    app.Run(":8080") // run application
}

Note that a margo.Application is merely a wrapper around gin.Engine, so you may use the underlying technology to its full extent.

Additional libraries

  • binder is a request binding middleware for margo.
  • jargo is a fully-featured jsonapi web framework built on top of margo.

Documentation

Overview

Package margo is a web framework providing a thin abstraction over the gin web framework.

It introduces the concept of handler functions returning Response values instead of directly setting headers or writing data to the response body. This makes it clear where handler functions write data, thus greatly improving code quality.

Basic Example:

type errorResponse struct {
	err error
}

// satisfies margo.Response
func (r *errorResponse) Send(context *gin.Context) error {
	context.String(http.StatusInternalServerError, "an internal server error occurred: %s", r.err.Error())
	return nil
}

func newErrorResponse(err error) margo.Response {
	return &errorResponse{
		err: err,
	}
}

func main() {
	// create new Application instance
	app := margo.NewApplication()

	// create endpoint handling the index route
	endpoint := margo.GET("/", func(context *gin.Context) margo.Response {
		// handle the request however you wish, for example
		// parse some request parameters
		params, err := parseQueryParams(context)
		if err != nil {
			// handle the error however you like,
			// for example by returning a generic error response
			// which implements margo.Response
			return newErrorResponse(err)
		}

		// do something with the retrieved params,
		// for example output them as json using
		// the builtin JSON function
		return margo.JSON(http.StatusOK, params)
	})
	app.Endpoint(endpoint) // register endpoint with Application

	app.Run(":8080") // run application
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Application

type Application struct {
	*gin.Engine
	// ErrorHandler is the ErrorHandlerFunc called when
	// a HandlerFunc in an Endpoint's HandlerChain
	// panics, or sending a Response returns an error.
	ErrorHandler ErrorHandlerFunc
}

An Application is a thin wrapper around a gin.Engine, providing additional utility methods.

func NewApplication

func NewApplication() *Application

NewApplication returns a new Application with the underlying gin.Engine being initialized using gin.New() and the default error handler.

func (*Application) Endpoint

func (s *Application) Endpoint(e Endpoint) gin.IRoutes

Endpoint exposes an Endpoint via HTTP.

type Endpoint

type Endpoint interface {
	// Method returns the Endpoint's HTTP method.
	Method() string
	// Path returns the Endpoint's URL.
	Path() string
	// Handlers returns a slice of handler functions
	// to be executed in order when the Endpoint is called.
	Handlers() HandlerChain
}

An Endpoint represents an HTTP endpoint that can be registered to an Application.

func DELETE

func DELETE(path string, handlers ...HandlerFunc) Endpoint

DELETE returns a new DELETE Endpoint for a path and at least one HandlerFunc.

func GET

func GET(path string, handlers ...HandlerFunc) Endpoint

GET returns a new GET Endpoint for a path and at least one HandlerFunc.

func NewEndpoint

func NewEndpoint(method string, path string, handlers ...HandlerFunc) Endpoint

NewEndpoint returns a new Endpoint for a given HTTP method and URL path, with at least one HandlerFunc to be executed when the Endpoint is called.

Panics if no HandlerFunc is provided.

func PATCH

func PATCH(path string, handlers ...HandlerFunc) Endpoint

PATCH returns a new PATCH Endpoint for a path and at least one HandlerFunc.

func POST

func POST(path string, handlers ...HandlerFunc) Endpoint

POST returns a new POST Endpoint for a path and at least one HandlerFunc.

func PUT

func PUT(path string, handlers ...HandlerFunc) Endpoint

PUT returns a new PUT Endpoint for a path and at least one HandlerFunc.

type ErrorHandlerFunc

type ErrorHandlerFunc func(context *gin.Context, r interface{})

ErrorHandlerFunc is a function handling any errors occurring during execution of an Endpoint's HandlerChain.

type HandlerChain

type HandlerChain []HandlerFunc

A HandlerChain is a slice of handler functions to be executed in order. If a HandlerFunc returns a Response value, the Response is sent to the client, otherwise, the next HandlerFunc in the chain is executed. The last HandlerFunc in the chain is expected to return a Response value.

func (HandlerChain) ToGinHandler

func (chain HandlerChain) ToGinHandler(errorHandler ErrorHandlerFunc) gin.HandlerFunc

ToGinHandler converts a HandlerChain into a single gin.HandlerFunc. If any of the chain's handlers panic or Response.Send returns an error, the error handler is invoked.

type HandlerFunc

type HandlerFunc func(context *gin.Context) Response

A HandlerFunc is a function to be called when an Endpoint is accessed.

type Response

type Response interface {
	// Send sends response data to an HTTP client via a gin.Context.
	// Any errors returned are handled by the Application's ErrorHandler.
	Send(context *gin.Context) error
}

A Response is responsible for sending data to an HTTP client.

When using margo, all writing of HTTP headers or content should happen in a Response's Send method, nowhere else in your app.

func Empty

func Empty(status int) Response

Empty returns a Response sending no data with the specified status code.

func JSON

func JSON(status int, data interface{}) Response

JSON returns a Response sending json-encoded data with the specified status code.

func JSON200

func JSON200(data interface{}) Response

JSON200 returns a Response sending json-encoded data with status code 200 OK.

func Redirect

func Redirect(code int, location string) Response

Redirect returns a Response redirecting the client to a given location with the given status code.

func SendFile

func SendFile(file *os.File) Response

SendFile returns a Response sending a file with status code 200 OK. The file is closed after sending the Response.

Jump to

Keyboard shortcuts

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