rest

package module
v0.0.0-...-95685ea Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2013 License: MIT Imports: 13 Imported by: 0

README

Go-Json-Rest

A quick and easy way to setup a RESTful JSON API

Build Status

Go-Json-Rest is a thin layer on top of net/http that helps building RESTful JSON APIs easily. It provides fast URL routing using Go-UrlRouter, and helpers to deal with JSON requests and responses. It is not a high-level REST framework that transparently maps HTTP requests to procedure calls, on the opposite, you constantly have access to the underlying net/http objects.

Features

  • Implemented as a net/http Handler. This standard interface allows combinations with other Handlers.
  • Fast URL routing using Go-UrlRouter. It implements the classic route description syntax using a scalable trie data structure.
  • Optional /.status endpoint for easy monitoring.
  • Examples

Install

This package is "go-gettable", just do:

go get github.com/ant0ine/go-json-rest

Example

package main
import (
        "github.com/ant0ine/go-json-rest"
        "net/http"
)
type User struct {
        Id   string
        Name string
}
func GetUser(w *rest.ResponseWriter, req *rest.Request) {
        user := User{
                Id:   req.PathParam("id"),
                Name: "Antoine",
        }
        w.WriteJson(&user)
}
func main() {
        handler := ResourceHandler{}
        handler.SetRoutes(
                rest.Route{"GET", "/users/:id", GetUser},
        )
        http.ListenAndServe(":8080", &handler)
}

More Examples

  • Countries Demo very simple GET, POST, DELETE operations
  • Users Demo the mapping to object methods
  • SPDY Demo SPDY using github.com/shykes/spdy-go

Documentation

Options

Things to enable in production:

  • Gzip compression (default: disabled)
  • Custom Logger (default: Go default)

Things to enable in development:

  • Json indentation (default: enabled)
  • Error stack trace in the response body (default: disabled)

The Status Endpoint

Inspired by memcached "stats", this optional feature can be enabled to help monitoring the service.

GET /.status returns something like:

{
  "Pid": 21732,
  "UpTime": "1m15.926272s",
  "UpTimeSec": 75.926272,
  "Time": "2013-03-04 08:00:27.152986 +0000 UTC",
  "TimeUnix": 1362384027,
  "StatusCodeCount": {
    "200": 53,
    "404": 11
  },
  "TotalCount": 64,
  "TotalResponseTime": "16.777ms",
  "TotalResponseTimeSec": 0.016777,
  "AverageResponseTime": "262.14us",
  "AverageResponseTimeSec": 0.00026214
}

Copyright (c) 2013 Antoine Imbert

MIT License

Documentation

Overview

A quick and easy way to setup a RESTful JSON API

Go-Json-Rest is a thin layer on top of net/http that helps building RESTful JSON APIs easily. It provides fast URL routing using https://github.com/ant0ine/go-urlrouter, and helpers to deal with JSON requests and responses. It is not a high-level REST framework that transparently maps HTTP requests to procedure calls, on the opposite, you constantly have access to the underlying net/http objects.

Example:

package main

import (
        "github.com/ant0ine/go-json-rest"
        "net/http"
)

type User struct {
        Id   string
        Name string
}

func GetUser(w *rest.ResponseWriter, req *rest.Request) {
        user := User{
                Id:   req.PathParam("id"),
                Name: "Antoine",
        }
        w.WriteJson(&user)
}

func main() {
        handler := ResourceHandler{}
        handler.SetRoutes(
                rest.Route{"GET", "/users/:id", GetUser},
        )
        http.ListenAndServe(":8080", &handler)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Error

func Error(w *ResponseWriter, error string, code int)

Produce an error response in JSON with the following structure, '{"Error":"My error message"}' The standard plain text net/http Error helper can still be called like this: http.Error(w, "error message", code)

func NotFound

func NotFound(w *ResponseWriter, r *Request)

Produce a 404 response with the following JSON, '{"Error":"Resource not found"}' The standard plain text net/http NotFound helper can still be called like this: http.NotFound(w, r.Request)

Types

type Request

type Request struct {
	*http.Request
	// map of parameters that have been matched in the URL Path.
	PathParams map[string]string
}

Inherit from http.Request, and provide additional methods.

func (*Request) DecodeJsonPayload

func (self *Request) DecodeJsonPayload(v interface{}) error

Read the request body and decode the JSON using json.Unmarshal

func (*Request) PathParam

func (self *Request) PathParam(name string) string

Provide a convenient access to the PathParams map

type ResourceHandler

type ResourceHandler struct {

	// If true, and if the client accepts the Gzip encoding, the response payloads
	// will be compressed using gzip, and the corresponding response header will set.
	EnableGzip bool

	// If true, the JSON payload will be written in one line with no space.
	DisableJsonIndent bool

	// If true, the status service will be enabled. Various stats and status will
	// then be available at GET /.status in a JSON format.
	EnableStatusService bool

	// If true, when a "panic" happens, the error string and the stack trace will be
	// printed in the 500 response body.
	EnableResponseStackTrace bool

	// If true, the record that is logged for each response will be printed as JSON
	// in the log. Convenient for log parsing.
	EnableLogAsJson bool

	// Custom logger, defaults to log.New(os.Stderr, "", log.LstdFlags)
	Logger *log.Logger
	// contains filtered or unexported fields
}

Implement the http.Handler interface and act as a router for the defined Routes. The defaults are intended to be developemnt friendly, for production you may want to turn on gzip and disable the JSON indentation.

func (*ResourceHandler) ServeHTTP

func (self *ResourceHandler) ServeHTTP(orig_writer http.ResponseWriter, orig_request *http.Request)

This makes ResourceHandler implement the http.Handler interface. You probably don't want to use it directly.

func (*ResourceHandler) SetRoutes

func (self *ResourceHandler) SetRoutes(routes ...Route) error

Define the Routes. The order the Routes matters, if a request matches multiple Routes, the first one will be used. Note that the underlying router is https://github.com/ant0ine/go-urlrouter.

type ResponseWriter

type ResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

Inherit from an object implementing the http.ResponseWriter interface, and provide additional methods.

func (*ResponseWriter) Write

func (self *ResponseWriter) Write(b []byte) (int, error)

Overloading of the http.ResponseWriter method. Provide additional capabilities, like transparent gzip encoding.

func (*ResponseWriter) WriteHeader

func (self *ResponseWriter) WriteHeader(code int)

Overloading of the http.ResponseWriter method. Just record the status code for logging.

func (*ResponseWriter) WriteJson

func (self *ResponseWriter) WriteJson(v interface{}) error

Encode the object in JSON, set the content-type header, and call Write.

type Route

type Route struct {

	// Any http method. It will be used as uppercase to avoid common mistakes.
	HttpMethod string

	// A string like "/resource/:id.json".
	// Placeholders supported are:
	// :param that matches any char to the first '/' or '.'
	// *splat that matches everything to the end of the string
	PathExp string

	// Code that will be executed when this route is taken.
	Func func(*ResponseWriter, *Request)
}

Used with SetRoutes.

func RouteObjectMethod

func RouteObjectMethod(http_method string, path_exp string, object_instance interface{}, object_method string) Route

Create a Route that points to an object method. It can be convenient to point to an object method instead of a function, this helper makes it easy by passing the object instance and the method name as parameters.

Directories

Path Synopsis
examples
countries
Demonstrate simple POST GET and DELETE operations The Curl Demo: curl -i -d '{"Code":"FR","Name":"France"}' http://127.0.0.1:8080/countries curl -i -d '{"Code":"US","Name":"United States"}' http://127.0.0.1:8080/countries curl -i http://127.0.0.1:8080/countries/FR curl -i http://127.0.0.1:8080/countries/US curl -i http://127.0.0.1:8080/countries curl -i -X DELETE http://127.0.0.1:8080/countries/FR curl -i http://127.0.0.1:8080/countries curl -i -X DELETE http://127.0.0.1:8080/countries/US curl -i http://127.0.0.1:8080/countries
Demonstrate simple POST GET and DELETE operations The Curl Demo: curl -i -d '{"Code":"FR","Name":"France"}' http://127.0.0.1:8080/countries curl -i -d '{"Code":"US","Name":"United States"}' http://127.0.0.1:8080/countries curl -i http://127.0.0.1:8080/countries/FR curl -i http://127.0.0.1:8080/countries/US curl -i http://127.0.0.1:8080/countries curl -i -X DELETE http://127.0.0.1:8080/countries/FR curl -i http://127.0.0.1:8080/countries curl -i -X DELETE http://127.0.0.1:8080/countries/US curl -i http://127.0.0.1:8080/countries
gae/gaecountries
Demonstrate a simple Google App Engine app The Curl Demo: curl -i -d '{"Code":"FR","Name":"France"}' http://127.0.0.1:8080/countries curl -i -d '{"Code":"US","Name":"United States"}' http://127.0.0.1:8080/countries curl -i http://127.0.0.1:8080/countries/FR curl -i http://127.0.0.1:8080/countries/US curl -i http://127.0.0.1:8080/countries curl -i -X DELETE http://127.0.0.1:8080/countries/FR curl -i http://127.0.0.1:8080/countries curl -i -X DELETE http://127.0.0.1:8080/countries/US curl -i http://127.0.0.1:8080/countries
Demonstrate a simple Google App Engine app The Curl Demo: curl -i -d '{"Code":"FR","Name":"France"}' http://127.0.0.1:8080/countries curl -i -d '{"Code":"US","Name":"United States"}' http://127.0.0.1:8080/countries curl -i http://127.0.0.1:8080/countries/FR curl -i http://127.0.0.1:8080/countries/US curl -i http://127.0.0.1:8080/countries curl -i -X DELETE http://127.0.0.1:8080/countries/FR curl -i http://127.0.0.1:8080/countries curl -i -X DELETE http://127.0.0.1:8080/countries/US curl -i http://127.0.0.1:8080/countries
spdy
Demonstrate how to use SPDY with github.com/shykes/spdy-go For a command line client, install spdycat from: https://github.com/tatsuhiro-t/spdylay Then: spdycat -v --no-tls -2 http://localhost:8080/users/0
Demonstrate how to use SPDY with github.com/shykes/spdy-go For a command line client, install spdycat from: https://github.com/tatsuhiro-t/spdylay Then: spdycat -v --no-tls -2 http://localhost:8080/users/0
users
Demonstrate how to use rest.RouteObjectMethod rest.RouteObjectMethod helps create a Route that points to an object method instead of just a function.
Demonstrate how to use rest.RouteObjectMethod rest.RouteObjectMethod helps create a Route that points to an object method instead of just a function.

Jump to

Keyboard shortcuts

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