goat

package module
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2016 License: MIT Imports: 4 Imported by: 1

README

Goat GoDoc Build Status Coverage Status

Goat is a minimalistic REST API server in Go. You can pronounce it like the goat, or go-at. Depends on how you like goats.

Contents

Usage

Parameters

You can use named parameters and access them through goat.Params, wich you can treat as any map[string]string.

package main

import (
    "net/http"

    "github.com/bahlo/goat"
)

func helloHandler(w http.ResponseWriter, r *http.Request, p goat.Params) {
    goat.WriteJSON(w, map[string]string{
        "hello": p["name"],
    })
}

func main() {
    r := goat.New()

    r.Get("/hello/:name", "hello_url", helloHandler)

    r.Run(":8080")
}
Subrouters

You can create subrouters to simplify your code

func main() {
    r := goat.New()

    r.Get("/hello/:name", "hello_url", helloHandler)

    sr := r.Subrouter("/user")
    {
        sr.Post("/login", "user_login_url", loginHandler)
        sr.Get("/logout", "user_logout_url", logoutHandler)
    }

    r.Run(":8080")
}
Indices

Every route can have a description (like user_login_url). These can be used to automagically generate an API index (like this). If you want to hide specific methods, just provide an empty string.

func main() {
    r := goat.New()

    r.Get("/", "", r.IndexHandler)
    r.Get("/hello/:name", "hello_url", helloHandler)

    sr := r.Subrouter("/user")
    {
        sr.Post("/login", "user_login_url", loginHandler)
        sr.Get("/logout", "user_logout_url", logoutHandler)
    }

    r.Run(":8080")
}

The above example would return the following response on /:

{
  "hello_url": "/hello/:name",
  "user_logout_url": "/user/logout"
}

Note: Indices are only supported for GET requests. Open an issue, if you want them on other methods, too

Middleware

You can easily include any middleware you like. A great guide to middleware is found here. Important is, that it's in the following format:

func(http.Handler) http.Handler

Example:

func main() {
    r := goat.New()

    r.Get("/hello/:name", "hello_url", helloHandler)
    r.Use(loggerMiddleware, gzipMiddleware)

    r.Run(":8080")
}
Wrapping middleware

Sometimes middleware isn't in the required format, so you have to build a wrapper around it. This example shows a wrapper around handlers.CombinedLoggingHandler from the Gorilla handlers:

func loggerMiddleware(h http.Handler) http.Handler {
    // Create logfile (you should check for errors)
    f, _ := os.Create("api.log")
    return handlers.CombinedLoggingHandler(f, h)
}

You can now safely use the middleware in Goat:

func main() {
    r := goat.New()

    r.Get("/hello/:name", "hello_url", helloHandler)
    r.Use(loggerMiddleware)

    r.Run(":8080")
}

Philosophy

I wanted to create a small, fast and reliable REST API server, which supports quick JSON and error output, good rooting and easy-to-use middleware.

I have split the files after responsibility to make it easy for everyone to dive in (start with goat.go).

Feedback

If you have problems, feel free to create an issue or drop me an email at hallo@arne.me!

Credits

Thanks to Julien Schmidt for the amazing httprouter used in this project.

License

This project is licensed unter MIT, for more information look into the LICENSE file.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WriteError

func WriteError(w http.ResponseWriter, code int, err string)

WriteError writes a string as JSON encoded error

func WriteJSON

func WriteJSON(w http.ResponseWriter, v interface{}) error

WriteJSON writes the given interface as JSON or returns an error

func WriteJSONWithStatus added in v1.0.7

func WriteJSONWithStatus(w http.ResponseWriter, code int, v interface{}) error

WriteJSONWithStatus writes the given statuscode into the header and the given interface as JSON or returns an error

Types

type Handle

type Handle func(http.ResponseWriter, *http.Request, Params)

Handle describes the function that should be used by handlers

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware reprents a default middleware function

type Params

type Params map[string]string

Params represents the parameters of a request

type Router

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

Router represents a router

func New

func New() *Router

New creates a new Router and returns it

func (*Router) Delete

func (r *Router) Delete(path, title string, fn Handle)

Delete adds a DELETE route

func (*Router) Get

func (r *Router) Get(path, title string, fn Handle)

Get adds a GET route

func (*Router) Index

func (r *Router) Index() map[string]string

Index returns a string map with the titles and urls of all GET routes

func (*Router) IndexHandler

func (r *Router) IndexHandler(w http.ResponseWriter, _ *http.Request, _ Params)

IndexHandler writes the index of all GET methods to the ResponseWriter

func (*Router) Options added in v1.0.3

func (r *Router) Options(path, title string, fn Handle)

Options adds a OPTIONS route

func (*Router) Post

func (r *Router) Post(path, title string, fn Handle)

Post adds a POST route

func (*Router) Put

func (r *Router) Put(path, title string, fn Handle)

Put adds a PUT route

func (*Router) Run

func (r *Router) Run(address string) error

Run starts the server

func (*Router) RunTLS added in v1.0.2

func (r *Router) RunTLS(addr, certFile, keyFile string) error

RunTLS starts the server, but expects HTTPS connections

func (*Router) ServeHTTP added in v1.0.3

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

ServeHTTP implements http.Handler

func (*Router) Subrouter

func (r *Router) Subrouter(path string) *Router

Subrouter creates and returns a subrouter

func (*Router) Use

func (r *Router) Use(middleware ...Middleware)

Use adds middleware to the router

Jump to

Keyboard shortcuts

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