Goat - A minimalistic JSON API server in Go

⚠️ DEPRECATED ⚠️

This project is no longer maintained, please use something like gorilla/mux or echo.


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 [email protected]!

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.

Owner
Arne Bahlo
he/him
Arne Bahlo
Comments
  • All routes showing in IndexHandler

    All routes showing in IndexHandler

    As per #9, I thought I could help as I liked that feature as well.

    • [X] Make all routes show up (not only GETs)
    • [X] Update tests

    What about displaying the method of each route? What could your suggested strategy be? This structure came up on top of my mind:

    {
      "hello_url": {
        "method": "GET",
        "path": "/hello/:name"
      },
      "user_logout_url": {
        "method": "POST",
        "path": "/user/logout"
      }
    }
    

    Do I have the :green_apple: light to go on?

  • Middleware logging response status code

    Middleware logging response status code

    Maybe it's just me, but I'm struggling with writing a middleware that is logging the http status code of the response that goat sent.

    Do you have any ideas how this can be accomplished?

  • Content-Type of goat.WriteJSON not application/json

    Content-Type of goat.WriteJSON not application/json

    The content-type header of goat.WriteJSON should be application/json, not text/plain. I am aware that I can set this header myself, but I think the function name WriteJSON suggests that this is already done there.

  • IndexHandler showing all routes

    IndexHandler showing all routes

    I think it would be nice if IndexHandler would return all routes and endpoints, not only GET ones. It would also be nice if they were sorted somehow (alphabetical by route maybe). I can't see an order here.

  • Add header tests, set headers correctly

    Add header tests, set headers correctly

    • Adds tests for the Content-Type-header
    • Fixes some comments
    • Sets headers in every JSON-related function correctly, completely fixing #4. :bug:

    Sorry I didn't really get what you meant with your first comment in #4, but I fixed it now :grin:

Fast JSON encoder/decoder compatible with encoding/json for Go
Fast JSON encoder/decoder compatible with encoding/json for Go

Fast JSON encoder/decoder compatible with encoding/json for Go

Jan 6, 2023
Package json implements encoding and decoding of JSON as defined in RFC 7159

Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions

Jun 26, 2022
Json-go - CLI to convert JSON to go and vice versa
Json-go - CLI to convert JSON to go and vice versa

Json To Go Struct CLI Install Go version 1.17 go install github.com/samit22/js

Jul 29, 2022
JSON Spanner - A Go package that provides a fast and simple way to filter or transform a json document

JSON SPANNER JSON Spanner is a Go package that provides a fast and simple way to

Sep 14, 2022
Fluent API to make it easier to create Json objects.

Jsongo Fluent API to make it easier to create Json objects. Install go get github.com/ricardolonga/jsongo Usage To create this: { "name":"Ricar

Nov 7, 2022
A library to query the godoc.org JSON API.

gopkg This repository provides minimal Go package that makes queries against the godoc.org JSON API. Since that site has mostly been subsumed by pkg.g

Dec 2, 2022
JSON:API compatible query string parser

QParser The package helps to parse part of the URL path and its parameters string to a handy structure. The structure format is compatible with the JS

Dec 21, 2021
A Simple JSON Description of Telegraph API
A Simple JSON Description of Telegraph API

telegraph-api-spec Introduction This golang program generates a JSON description of methods, types and docstrings of the Telegraph API. Features Easy

Nov 21, 2022
Abstract JSON for golang with JSONPath support

Abstract JSON Abstract JSON is a small golang package provides a parser for JSON with support of JSONPath, in case when you are not sure in its struct

Jan 5, 2023
Fast JSON parser and validator for Go. No custom structs, no code generation, no reflection

fastjson - fast JSON parser and validator for Go Features Fast. As usual, up to 15x faster than the standard encoding/json. See benchmarks. Parses arb

Jan 5, 2023
Small utility to create JSON objects
Small utility to create JSON objects

gjo Small utility to create JSON objects. This was inspired by jpmens/jo. Support OS Mac Linux Windows Requirements Go 1.1.14~ Git Installtion Build $

Dec 8, 2022
A Go package for handling common HTTP JSON responses.

go-respond A Go package for handling common HTTP JSON responses. Installation go get github.com/nicklaw5/go-respond Usage The goal of go-respond is to

Sep 26, 2022
JSON query in Golang

gojq JSON query in Golang. Install go get -u github.com/elgs/gojq This library serves three purposes: makes parsing JSON configuration file much easie

Dec 28, 2022
Automatically generate Go (golang) struct definitions from example JSON

gojson gojson generates go struct definitions from json or yaml documents. Example $ curl -s https://api.github.com/repos/chimeracoder/gojson | gojson

Jan 1, 2023
A JSON diff utility

JayDiff A JSON diff utility. Install Downloading the compiled binary Download the latest version of the binary: releases extract the archive and place

Dec 11, 2022
Fast and flexible JSON encoder for Go
Fast and flexible JSON encoder for Go

Jettison Jettison is a fast and flexible JSON encoder for the Go programming language, inspired by bet365/jingo, with a richer features set, aiming at

Dec 21, 2022
Create go type representation from json

json2go Package json2go provides utilities for creating go type representation from json inputs. Json2go can be used in various ways: CLI tool Web pag

Dec 26, 2022
Console JSON formatter with query feature
Console JSON formatter with query feature

Console JSON formatter with query feature. Install: $ go get github.com/miolini/jsonf Usage: Usage of jsonf: -c=true: colorize output -d=false: de

Dec 4, 2022
Arbitrary transformations of JSON in Golang

kazaam Description Kazaam was created with the goal of supporting easy and fast transformations of JSON data with Golang. This functionality provides

Dec 18, 2022