All Projects → nicklaw5 → go-respond

nicklaw5 / go-respond

Licence: MIT License
A Go package for handling common HTTP JSON responses.

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to go-respond

redbull
Develop JSON endpoints fast!
Stars: ✭ 11 (-75.56%)
Mutual labels:  json-api
accessibility-cloud
👩🏽‍🦯🦮👩🏻‍🦽👩🏿‍🦼 the platform to exchange physical accessibility data in a standardized, future-proof, easy-to-use way.
Stars: ✭ 37 (-17.78%)
Mutual labels:  json-api
jsonapi-deserializable
Conveniently deserialize JSON API payloads into custom hashes.
Stars: ✭ 23 (-48.89%)
Mutual labels:  json-api
lurch
A simple Ruby JSON API client.
Stars: ✭ 15 (-66.67%)
Mutual labels:  json-api
nfw
A jsonapi boilerplate for @nfw-core with mikro-orm
Stars: ✭ 23 (-48.89%)
Mutual labels:  json-api
basic-transport-info-app
A progressive web app to show direct & indirect buses / transport between two places / cities / stops .Show next schedule & travel duration. Algorithm to calculate indirect buses on basis of their schedule time. Voice search . Locate nearest city/stop by gps. Bus timetable.
Stars: ✭ 12 (-73.33%)
Mutual labels:  json-api
jsonapi
Set of tools to build a JSON:API compliant service.
Stars: ✭ 19 (-57.78%)
Mutual labels:  json-api
motis
Intermodal Mobility Information System
Stars: ✭ 45 (+0%)
Mutual labels:  json-api
DocDex
JSON API & Discord Bot for Javadocs
Stars: ✭ 31 (-31.11%)
Mutual labels:  json-api
JSONCustomLintr
Library to allow creation, running, and reporting of custom lint rules for JSON files
Stars: ✭ 19 (-57.78%)
Mutual labels:  json-api
w3c-api
The W3C API
Stars: ✭ 130 (+188.89%)
Mutual labels:  json-api
whc-json-to-class
javascript版本json自动转换生成对应语言模型类The whc-json-to-class is the javascript plug-in that automatically converts the json string to the corresponding language model class
Stars: ✭ 24 (-46.67%)
Mutual labels:  json-api
Perfect-JSON-API
An Example JSON API for Perfect
Stars: ✭ 43 (-4.44%)
Mutual labels:  json-api
app
Quick start JSON API application
Stars: ✭ 80 (+77.78%)
Mutual labels:  json-api
biolink-model
Schema and generated objects for biolink data model and upper ontology
Stars: ✭ 83 (+84.44%)
Mutual labels:  json-api
ck-web
Collective Knowledge web extension to browse CK repositories, visualize interactive graphs and articles, render CK-based websites, implement simple web services with JSON API (for example to crowdsource experiments or unify access to DNN). Demos of interactive articles, graphs and crowdsourced experiments:
Stars: ✭ 31 (-31.11%)
Mutual labels:  json-api
laravel5-jsonapi-dingo
Laravel5 JSONAPI and Dingo together to build APIs fast
Stars: ✭ 29 (-35.56%)
Mutual labels:  json-api
aiohttp json api
JSON API implementation for aiohttp
Stars: ✭ 18 (-60%)
Mutual labels:  json-api
Vox
Swift JSON:API client framework
Stars: ✭ 47 (+4.44%)
Mutual labels:  json-api
json
a portable, powerful and pure functional JSON library for Scheme
Stars: ✭ 40 (-11.11%)
Mutual labels:  json-api

go-respond

A Go package for handling common HTTP JSON responses.

GoDoc Build Status Coverage Status Go Report Card

Installation

go get github.com/nicklaw5/go-respond

Usage

The goal of go-respond is to take most of the grunt work out preparing your JSON response. Here's a simple example:

package main

import (
    "net/http"

    resp "github.com/nicklaw5/go-respond"
)

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func main() {
    http.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
        users := []User{
            {1, "Billy", "[email protected]"},
            {2, "Joan", "[email protected]"},
        }

        resp.NewResponse(w).Ok(users)
    })

    http.ListenAndServe(":8080", nil)
}

Response Methods

Response Code Method Name
200 Ok()
201 Created()
202 Accepted()
204 NoContent()
400 BadRequest()
401 Unauthorized()
403 Forbidden()
404 NotFound()
405 MethodNotAllowed()
406 NotAcceptable()
409 Conflict()
410 Gone()
411 LengthRequired()
412 PreconditionFailed()
413 RequestEntityTooLarge()
415 UnsupportedMediaType()
422 UnprocessableEntity()
500 InternalServerError()
501 NotImplemented()
502 BadGateway()
503 ServiceUnavailable()
504 GatewayTimeout()

See here for a complete list of HTTP responses, along with an explanation of each.

Please submit a PR if you want to add to this list. Only the most common response types have been included.

To Long, Don't Write

Sometimes you don't need to return a specific content-message but don't want the response body to be empty. In this case you can use the DefaultMessage() for responding with json containing the default message for the corresponding status code.

package main

import (
    "net/http"
    resp "github.com/nicklaw5/go-respond"
)

func main() {
    http.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
        // ...
        if !authenticated {
            resp.NewResponse(w).DefaultMessage().
                Unauthorized(nil)
        }
        // ...
    })
    http.ListenAndServe(":8080", nil)
}

Would respond with {"status":401,"message":"Unauthorized"}

Handling Errors

The best option for handling errors that may occur while marshalling the JSON response, is to use Negroni's Recovery middleware. Here's an example:

package main

import (
    "net/http"

    "github.com/urfave/negroni"
    resp "github.com/nicklaw5/go-respond"
)

type Response struct {
    Success bool `json:"success"`
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        resp.NewResponse(w).Ok(&Response{true})
    })

    n := negroni.New()
    recovery := negroni.NewRecovery()
    recovery.ErrorHandlerFunc = func(error interface{}) {
        // do something with the unexpected error
    }

    n.Use(recovery)
    n.UseHandler(mux)

    http.ListenAndServe(":8080", n)
}

License

This package is distributed under the terms of the MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].