go-restful

repository·v3·Indexed 26 days ago

https://github.com/emicklei/go-restful

A Go package for building REST-style Web Services. It provides a structured way to map HTTP methods and paths to handler functions with support for path parameters, media types, and routing complexities. Key features include a fast default router (CurlyRouter), middleware filters, automatic CORS and OPTIONS handling, customizable panic recovery, and content encoding (gzip/deflate) via the CompressorProvider interface.

Tokens
10.5K
Snippets
25
Records
108
Agent score
86%

What's inside go-restful

  1. Overview of go-restful features

    v3

    go-restful is a package for building REST-style Web Services in Go. Key features include:

    • Routing: Supports path parameters (e.g., {id}), prefixes, and suffixes. Includes a fast default router supporting Google custom methods and regular expressions.
    • Request/Response API: Easy access to path, query, and header parameters, and writing structs to JSON/XML.
    • Middleware & Filters: Intercept request/response flows at the Service or Route level. Supports injecting http.Handler via HttpMiddlewareHandlerToFilter.
    • Automatic Handling: Built-in support for CORS, OPTIONS requests, and panic recovery (customizable via RecoverHandler(...)).
    • Encoding: Customizable encoding via EntityReaderWriter and compression (gzip/deflate) via CompressorProvider registration.
    • Error Handling: Customizable route errors via ServiceErrorHandler(...) and panic recovery via RecoverHandler(...).
  2. Customize go-restful behavior

    v3

    The package provides several hooks for customization:

    • Router: Change the routing algorithm.
    • Panic Recovery: Use RecoverHandler(...) to customize how panics are handled.
    • Error Handling: Use ServiceErrorHandler(...) to customize route errors.
    • Encoding/Compression: Register custom JSON decoders, EntityReaderWriter for new serializers, or CompressorProvider for custom gzip/deflate behavior.
    • Logging: Configure trace logging.
    • Slash Matching: Control whether routes ending in a slash / match using the TrimRightSlashEnabled package variable (defaults to true).
  3. Define a WebService and Routes

    v3

    You can build RESTful services by creating a restful.WebService instance, defining its base path, supported media types (Consumes/Produces), and registering routes that map HTTP methods and paths to handler functions.

    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{}))
    
    // Handler implementation
    func (u UserResource) findUser(request *restful.Request, response *restful.Response) {
    	id := request.PathParameter("user-id")
    	...
    }
  4. Configure TrimRightSlashEnabled behavior

    v3
    The global variable TrimRightSlashEnabled (defaults to true) controls how paths are processed. When true, it affects both route building (using path.Join) and how the incoming request path is trimmed of its trailing slash. This setting is used to maintain compatibility with older versions of the library.
  5. Note on EnableContentEncoding

    v3

    The global variable restful.EnableContentEncoding is OBSOLETE.

    Instead of toggling this variable, use restful.DefaultContainer.EnableContentEncoding(true) to change the content encoding setting in your container.

  6. Use Do() for DRY route configuration

    v3

    The Do method allows you to apply a set of configuration steps to a RouteBuilder using a reusable function. This helps follow DRY (Don't Repeat Yourself) principles when multiple routes share common documentation or response patterns.

    // Reusable configuration block
    func StandardErrors(b *restful.RouteBuilder) {
        b.Returns(500, "Internal Server Error", ErrorModel{})
        b.Returns(401, "Unauthorized", nil)
    }
    
    // Usage in route definition
    ws.Route(ws.GET("/").To(myHandler).Do(StandardErrors))
    ws.Route(ws.DELETE("/{name}").To(t.deletePerson).Do(Returns200, Returns500))
    
    func Returns500(b *RouteBuilder) {
        b.Returns(500, "Internal Server Error", restful.ServiceError{})
    }
  7. Configure Parameter constraints and metadata

    v3

    The Parameter type allows you to set detailed metadata and validation constraints for your API documentation:

    • Basic Metadata: Description(string), DataType(string), DataFormat(string), DefaultValue(string).
    • Validation: Pattern(string), Minimum(float64), Maximum(float64), MinLength(int64), MaxLength(int64), MinItems(int64), MaxItems(int64), UniqueItems(bool).
    • Requirement & Multiplicity: Required(bool), AllowMultiple(bool), AllowEmptyValue(bool).
    • Values: PossibleValues([]string) sets a list of allowed values. (Note: AllowableValues(map[string]string) is deprecated but still functional and maps to PossibleValues).
  8. Configure panic recovery behavior in DefaultContainer

    v3

    By default, the DefaultContainer recovers from panics and returns an HTTP 500 error. To disable this behavior (which may improve performance but requires Route functions to handle all errors manually), use the DoNotRecover(true) method on the DefaultContainer instance.

    Note: The package-level variable DoNotRecover is obsolete.

    restful.DefaultContainer.DoNotRecover(true)
  9. Enable content encoding for a Route

    v3
    You can enable GZIP or DEFLATE encoding for a specific route by calling EnableContentEncoding(enabled bool). This setting overrides the global container's contentEncodingEnabled value.