go-restful is a free, open source api development & testing project written in Go and released under MIT. It has 5,115 GitHub stars, 678 forks and 2 open issues, and was last pushed 10 days ago. On this registry it ranks #46 of 103 tracked projects in API Development & Testing, with 5 head-to-head comparisons available.

What is go-restful?

go-restful is an MIT-licensed Go package for building REST-style web services in which the HTTP methods map one-to-one onto create, read, update and delete operations, and it is aimed at Go developers who want explicit, customizable control over routing, request parsing, response encoding and filter chains.

What it is

go-restful is a library in the Go ecosystem for building REST-style web services. It declares a WebService with Path, Consumes and Produces, registers routes that map an HTTP method and path to a handler function, and mounts those services on a Container. The project spans the routing layer, a Request API for reading structs from JSON or XML and for reading path, query and header parameters, a Response API for writing structs and setting headers, and a filter mechanism for intercepting the request-to-response flow. Its module path for current releases is github.com/emicklei/go-restful/v3, and its topic list is customizable, go, openapi, rest and routing.

The concrete problem it solves is dispatch: without it, a Go service has to hand-match HTTP verbs and URL paths to functions and hand-decode bodies before any handler logic runs. go-restful replaces that manual wiring with declarative routes such as ws.GET("/{user-id}").To(u.findUser) and ws.PathParameter("user-id", "identifier of the user").DataType("string"), along with the encoding and error handling around them. It also offers an API declaration path to Swagger UI through the companion project go-restful-openapi, so the same route definitions can feed generated documentation instead of a separately maintained specification.

Key capabilities

  • Routes map a request to a function with path parameters in several forms: {id}, prefix_{var} and {var}_suffix.
  • Configurable router: the default fast algorithm supports static elements, Google custom methods, regular expressions and dynamic parameters such as /resource/name:customVerb, /meetings/{id} and /static/{subpath:*}; an alternative algorithm after JSR311 is implemented using regular expressions but does not accept them in route definitions.
  • Request API reads structs from JSON and XML and exposes path, query and header parameters; Response API writes structs to JSON and XML and sets headers, with encodings named as restful.MIME_XML and restful.MIME_JSON.
  • Customizable encoding through EntityReaderWriter registration, and customizable gzip and deflate readers and writers through CompressorProvider registration.
  • Filters intercept the request-to-response flow at either Service or Route level, and request-scoped variables are held in attributes.
  • Container type hosts WebServices on different HTTP endpoints, and content encoding (gzip, deflate) applies to request and response payloads.
  • Panic recovery produces an HTTP 500 customizable via RecoverHandler(...), while route errors produce HTTP 404, 405, 406 or 415 customizable via ServiceErrorHandler(...); automatic OPTIONS responses and automatic CORS handling are available as filters.

Who uses it and how

  • Go teams building HTTP APIs who prefer explicit route declarations over a larger framework, using WebService, Route and Container to structure handlers.
  • Projects that need generated OpenAPI or Swagger UI output, adopting go-restful-openapi alongside the routes they already declared.
  • Services exposing several HTTP endpoints side by side, using one Container per endpoint rather than a single global mux.
  • Services that must serve both JSON and XML, or that need gzip and deflate request and response payloads, configuring this per WebService with Consumes and Produces.
  • Codebases moving onto Go modules, which must be on the v3 major version because versions up to v2.*.* on master do not support modules.

Getting started

Go modules users import the package as restful "github.com/emicklei/go-restful/v3", which is supported as of version v3.0.0 on the v3 branch. Previously it was imported as restful "github.com/emicklei/go-restful" without modules, and working code examples for v3 live in the repository's examples directory.

How it compares

No list of paid products replaced by this project is provided, so a comparison on licence, self-hosting, data ownership and cost model cannot be made from the available facts. Among similar tools, the facts name only go-restful-openapi, which is a companion library for API declaration rather than an alternative; otherwise go-restful stands alone in this registry.

When to use it — and when not to

This is a library rather than a hosted service, so a self-hoster operates no database, object storage or SMTP component on its behalf — the operational burden is the Go process and whatever infrastructure the surrounding application already uses. Teams that want a framework supplying templating, persistence and administrative scaffolding should look elsewhere, because the README covers routing, encoding, filters and error handling and stops there. Pick v3 deliberately when moving to Go modules, since the master-line versions up to v2.*.* do not support them, and note that the customization section of the README is presented as a list of hooks rather than as worked configuration examples.

project readme (upstream, from github) — read inline

go-restful

package for building REST-style Web Services using Google Go

Go Reference codecov

REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping:

  • GET = Retrieve a representation of a resource
  • POST = Create if you are sending content to the server to create a subordinate of the specified resource collection, using some server-side algorithm.
  • PUT = Create if you are sending the full content of the specified resource (URI).
  • PUT = Update if you are updating the full content of the specified resource.
  • DELETE = Delete if you are requesting the server to delete the resource
  • PATCH = Update partial content of a resource
  • OPTIONS = Get information about the communication options for the request URI

Usage

Without Go Modules

All versions up to v2.*.* (on the master) are not supporting Go modules.

import (
	restful "github.com/emicklei/go-restful"
)
Using Go Modules

As of version v3.0.0 (on the v3 branch), this package supports Go modules.

import (
	restful "github.com/emicklei/go-restful/v3"
)

Example

ws := new(restful.WebService)
ws.
	Path("/users").
	Consumes(restful.MIME_XML, restful.MIME_JSON).
	Produces(restful.MIME_JSON, restful.MIME_XML)

ws.Route(ws.GET("/{user-id}").To(u.findUser).
	Doc("get a user").
	Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")).
	Writes(User{}))		
...
	
func (u UserResource) findUser(request *restful.Request, response *restful.Response) {
	id := request.PathParameter("user-id")
	...
}

Full API of a UserResource

Features

  • Routes for request → function mapping with path parameter (e.g. {id} but also prefix_{var} and {var}_suffix) support
  • Configurable router:
    • (default) Fast routing algorithm that allows static elements, google custom method, regular expressions and dynamic parameters in the URL path (e.g. /resource/name:customVerb, /meetings/{id} or /static/{subpath:*})
    • Routing algorithm after JSR311 that is implemented using (but does not accept) regular expressions
  • Request API for reading structs from JSON/XML and accessing parameters (path,query,header)
  • Response API for writing structs to JSON/XML and setting headers
  • Customizable encoding using EntityReaderWriter registration
  • Filters for intercepting the request → response flow on Service or Route level
  • Request-scoped variables using attributes
  • Containers for WebServices on different HTTP endpoints
  • Content encoding (gzip,deflate) of request and response payloads
  • Automatic responses on OPTIONS (using a filter)
  • Automatic CORS request handling (using a filter)
  • API declaration for Swagger UI (go-restful-openapi)
  • Panic recovery to produce HTTP 500, customizable using RecoverHandler(...)
  • Route errors produce HTTP 404/405/406/415 errors, customizable using ServiceErrorHandler(...)
  • Configurable (trace) logging
  • Customizable gzip/deflate readers and writers using CompressorProvider registration
  • Inject your own http.Handler using the HttpMiddlewareHandlerToFilter function
  • Added SetPathTokenCacheEnabled and SetCustomVerbCacheEnabled to disable regexp caching (default=true)

How to customize

There are several hooks to customize the behavior of the go-restful package.

  • Router algorithm
  • Panic recovery
  • JSON decoder
  • Trace logging
  • Compression
  • Encoders for other serializers
  • Use the package variable TrimRightSlashEnabled (default true) to control the behavior of matching routes that end with a slash /

Resources

Type git shortlog -s for a full list of contributors.

© 2012 - 2023, http://ernestmicklei.com. MIT License. Contributions are welcome.

Frequently asked questions

Is go-restful free to use?

go-restful is open source under the MIT licence. There is no licence fee and no seat count — you can self-host it or, where the project offers one, pay a vendor for a managed version instead.

What does go-restful do?

package for building REST-style Web Services using Go

What is go-restful written in?

go-restful is primarily written in Go. Its source is publicly available at https://github.com/emicklei/go-restful, and it has 5,115 GitHub stars.