# README
Go-Relax

Build fast and complete RESTful APIs in Go
Go-Relax aims to provide the tools to help developers build RESTful web services, and information needed to abide by REST architectural constraints using correct HTTP semantics.
Quick Start
Install using "go get":
go get github.com/srfrog/go-relax
Then import from your source:
import "github.com/srfrog/go-relax"
View example_test.go for an extended example of basic usage and features.
Also, check the wiki for HowTo's and recipes.
Features
- Helps build API's that follow the REST concept using ROA principles.
- Built-in support of HATEOAS constraint with Web Linking header tags.
- Follows REST "best practices", with inspiration from Heroku and GitHub.
- Works fine along with
http.ServeMux
or independently ashttp.Handler
- Supports different media types, and mixed for requests and responses.
- It uses JSON media type by default, but also includes XML (needs import).
- The default routing engine uses trie with regexp matching for speed and flexibility.
- Comes with a complete set of filters to build a working API. "Batteries included"
- Uses
sync.pool
to efficiently use resources when under heavy load.
Included filters
- Content - handles mixed request/response encodings, language preference, and versioning.
- Basic authentication - to protect any resource with passwords.
- CORS - Cross-Origin Resource Sharing, for remote client-server setups.
- ETag - entity tagging with conditional requests for efficient caching.
- GZip - Dynamic gzip content data compression, with ETag support.
- Logging - custom logging with pre- and post- request event support.
- Method override - GET/POST method override via HTTP header and query string.
- Security - Various security practices for request handling.
- Limits - request throttler, token-based rate limiter, and memory limits.
Upcoming filters
- JSON-API support.
- JSON-Schema for validating requests and responses.
- Collection-JSON support.
Documentation
The full code documentation is located at GoDoc:
https://pkg.go.dev/github.com/srfrog/go-relax
The source code is thoroughly commented, have a look.
Hello World
This minimal example creates a new Relax service that handles a Hello resource.
package main
import (
"github.com/srfrog/go-relax"
)
type Hello string
func (h *Hello) Index(ctx *relax.Context) {
ctx.Respond(h)
}
func main() {
h := Hello("hello world!")
svc := relax.NewService("http://api.company.com/")
svc.Resource(&h)
svc.Run()
}
$ curl -i -X GET http://api.company.com/hello
Response:
HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8
Link: </hello>; rel="self"
Link: </hello>; rel="index"
Request-Id: 61d430de-7bb6-4ff8-84da-aff6fe81c0d2
Server: Go-Relax/0.5.0
Date: Thu, 14 Aug 2014 06:20:48 GMT
Content-Length: 14
"hello world!"
Credits
Go-Relax is Copyright (c) Codehack. Published under an MIT License
# Functions
GetRealIP returns the client address if the request is proxied.
InternalServerError responds with HTTP status code 500-"Internal Server Error".
IsRequestSSL returns true if the request 'r' is done via SSL/TLS.
LinkHeader returns a complete Link header value that can be plugged into http.Header().Add().
NewEncoder returns an EncoderJSON object.
NewRequestID returns a new request ID value based on UUID; or checks an id specified if it's valid for use as a request ID.
NewResponseBuffer returns a ResponseBuffer object initialized with the headers of 'w', an object that implements ``http.ResponseWriter``.
NewService returns a new Service that can serve resources.
ParsePreferences is a very naive and simple parser for header value preferences.
PathExt returns the media subtype extension in an URL path.
# Constants
StatusNetworkAuthenticationRequired indicates that the client needs to authenticate to gain network access.
StatusPreconditionRequired indicates that the origin server requires the request to be conditional.
StatusRequestHeaderFieldsTooLarge indicates that the server is unwilling to process the request because its header fields are too large.
StatusTooManyRequests indicates that the user has sent too many requests in a given amount of time ("rate limiting").
StatusUnprocessableEntity indicates the user sent content that while it is syntactically correct, it might be erroneous.
Version is the version of this package.
# Variables
Content does content negotiation to select the supported representations
for the request and response.
ErrBodyTooLarge is returned by Encoder.Decode when the read length exceeds the maximum size set for payload.
ErrRouteBadMethod is returned when the path did not match a given HTTP method.
ErrRouteNotFound is returned when the path searched didn't reach a resource handler.
# Structs
Context has information about the request and filters.
EncoderJSON implements the Encoder interface.
Link an HTTP header tag that represents a hypertext relation link.
Resource is an object that implements Resourcer; serves requests for a resource.
ResponseBuffer implements http.ResponseWriter, but redirects all
writes and headers to a buffer.
Service contains all the information about the service and resources handled.
StatusError is an error with a HTTP Status code.
# Interfaces
CRUD is an interface for Resourcer objects that provide create, read, update, and delete operations; also known as CRUD.
Encoder objects provide new data encoding formats.
Filter is a function closure that is chained in FILO (First-In Last-Out) order.
LimitedFilter are filters that only can be used with a set of resources.
Logger interface is based on Go's ``log`` package.
Optioner is implemented by Resourcer objects that want to provide their own response to OPTIONS requests.
Resourcer is any object that implements the this interface.
Router defines the routing system.
# Type aliases
HandlerFunc is simply a version of http.HandlerFunc that uses Context.