webapi

package module
v0.0.0-...-38dbd55 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2020 License: MIT Imports: 3 Imported by: 2

README

Web API

Golang Web API Framework

Purpose

The Project "webapi" is a Go Module with the purpose of creating feature rich web apis with little effort. It extends the functionality of the net/http package and adds a Router that implements the net/http.Handler interface. The Router can be used in the context of a net/http.Server to route HTTP(S) requests to a specific handler by using regex matchers that are defined in the powerful, yet easy to understand Path-To-Regexp Syntax. With Path-To-Regexp, the Router is also capable of parsing Path Parameters that are defined in the route's matcher string, (see example or test cases). The path parameters will be passed as a map[string]string to any of the given request handlers. The framework defines new Handler functions that are more flexible than net/http.HandlerFunc's and allow the programmer to create chained handlers with customizable alternative paths (e.g. Error Handlers). See examples for more info...

Usage

Simply go get the package and start coding:

go get https://github.com/markoczy/webapi

Here's a minimalistic usage example:

// Create Fallback handler (for unmatched requests)
fallback404 := webapi.NewErrorHandler(http.StatusNotFound, "404 not found")
// Create Router
router := webapi.NewRouter(fallback404)
// Create Handler by chaining Handler functions
handler := webapi.NewHandler(
    // Handler function 1
    func(w http.ResponseWriter, r *webapi.ParsedRequest, next func() webapi.Handler) webapi.Handler {
        // (optional) Handle errors
        if r.PathParams["name"] == "abc" {
            return webapi.NewErrorHandler(http.StatusBadRequest, "Your name is not 'abc' ;-)") 
        }
        // Write data (or do other stuff)
        w.Write([]byte("Hello, " + r.PathParams["name"]))
        return next()
    }, 
    // Handler function 2
    func(w http.ResponseWriter, r *webapi.ParsedRequest, next func() webapi.Handler) webapi.Handler {
        // do stuff for handler 2 (e.g. Fill Headers)
        return next()
    },
)
// Register Handler
router.Handle(http.MethodGet, "/hello/:name", handler)
// Serve HTTP
http.ListenAndServe(":7890", router)
//
// cURL Results:
// `curl localhost:7890/hello/John+Doe` returns Hello, John Doe
// `curl localhost:7890/hello/abc` returns Bad Request

For Path matching syntax, check github.com/soongo/path-to-regexp, for more examples, check the test cases.

Dependencies

  • PathToRegexp: github.com/soongo/path-to-regexp (License: MIT)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

type Handler interface {
	// Handle calls the current handler.
	Handle(w http.ResponseWriter, r *ParsedRequest, next func() Handler) Handler
	// HandleAll calls the current handler and all following handlers.
	HandleAll(w http.ResponseWriter, r *ParsedRequest)
	// Next returns the following handler.
	Next() Handler
}

Handler is an interface that defines any request handler of this Framework. The handlers are used by the router to process HTTP Requests.

func NewErrorHandler

func NewErrorHandler(code int, err string) Handler

NewErrorHandler creates an error handler according to the net/http default implementation

func NewHandler

func NewHandler(firstHandler HandlerFunc, optionalHandlers ...HandlerFunc) Handler

NewHandler creates a HTTP handler from default implementation. It takes one or more Handler Functions that act as middleware for the handler.

func NewNativeHandler

func NewNativeHandler(handler http.Handler) Handler

NewNativeHandler creates a handler from a net/http Handler.

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *ParsedRequest, next func() Handler) Handler

HandlerFunc is the definition of any Handler of this Web API framework the function `next()` returns the next handler to call, it is usually returned in any non-error case, otherwise an error handler should be returned instead.

func NewNativeHandlerFunc

func NewNativeHandlerFunc(handler http.Handler) HandlerFunc

NewNativeHandlerFunc creates an intermediate Handler from a net/http Handler.

type ParsedRequest

type ParsedRequest struct {
	PathParams map[string]string
	Request    *http.Request
	State      interface{}
}

ParsedRequest is an enriched version of the native http.Request which contains the parsed PathParams as well as an optional State Variable to exchange Data between successive Handlers.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router is a type used to route HTTP Requests to a specific handler. The router is also capable of parsing path params if the routeConfig's regex supports named capture groups.

func NewRouter

func NewRouter(fallback Handler) *Router

NewRouter creates a new Router.

func (*Router) Handle

func (router *Router) Handle(method, matcher string, handler Handler)

Handle registers a handler for a given request type.

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the net/http Handler interface so that the Router can be used as native net/http Handler.

Jump to

Keyboard shortcuts

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