versioning

package
v14.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 9 Imported by: 0

README

API Versioning

This middleware routes a request to the handler that matches the API version the client asked for, so several versions of the same endpoint can live side by side.

What is API Versioning?

API versioning lets you change an API without breaking the clients already using it. Existing clients keep calling the version they were built against while you ship the next one.

For more information, you can refer to the API versioning Wikipedia page.

How to use the Iris Versioning Middleware?

To use the Iris API versioning middleware, we need to do the following:

  • Import the github.com/kataras/iris/v14/middleware/versioning package, which provides an Iris middleware for versioning.
  • Use the versioning.New function to create an iris.Handler and register it in our Iris app.

First, we need to install the Iris Web Framework, which contains the middleware too:

go get github.com/kataras/iris/v14@latest

Then, we need to import it in our main.go file:

import (
    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/versioning"
    "github.com/kataras/iris/v14/rest/errors"
)

Next, we need to use the versioning.New function to create an

iris.Handler. The function takes an Options struct that allows us to configure the versioning middleware. The Options struct includes fields such as Default, Latest, Strict, Versions, Deprecation, Header, QueryParam, Subdomain, NotFoundHandler, and Skipper. We can use the following code to create the handler:

opts := versioning.Options{
    Default: "1.0.0",
    Latest:  "2.0.0",
    Strict:  false,
    Header:  "Accept-Version",
    QueryParam: "v",
    Subdomain: false,
    NotFoundHandler: errors.DefaultVersioningNotFoundHandler,
    Deprecation: versioning.DeprecationOptions{
        WarnMessage:     "WARNING! You are using a deprecated version of this API.",
        DeprecationDate: time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC),
        DeprecationInfo: "A newer version is available.",
    },
    Versions: versioning.Versions{
        {
            Range:      ">=1.0.0 <2.0.0",
            Path:       "/v1",
            Deprecated: true,
        },
        {
            Range: ">=2.0.0",
            Path:  "/v2",
        },
    },
}

versioningMiddleware := versioning.New(opts)

Finally, we need to register the versioning middleware in our Iris app. We can use the app.UseRouter method to apply the middleware on every route. For example:

// Create an Iris app instance.
app := iris.New()

// Apply the versioning middleware.
app.UseRouter(versioningMiddleware)

// Define versioned routes.
v1 := app.Router("/v1")
{
    v1.Get("/", func(ctx iris.Context) {
        ctx.WriteString("Hello from version 1")
    })
}

v2 := app.Router("/v2")
{
    v2.Get("/", func(ctx iris.Context) {
        ctx.WriteString("Hello from version 2")
    })
}

// Start the server.
app.Listen(":8080")

Example

Here is a complete example of how to use versioning middleware with Iris:

package main

import (
    "time"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/versioning"
    "github.com/kataras/iris/v14/rest/errors"
)

func main() {
    app := iris.New()

    opts := versioning.Options{
        Default: "1.0.0",
        Latest:  "2.0.0",
        Strict:  false,
        Header:  "Accept-Version",
        QueryParam: "v",
        Subdomain: false,
        NotFoundHandler: errors.DefaultVersioningNotFoundHandler,
        Deprecation: versioning.DeprecationOptions{
            WarnMessage:     "WARNING! You are using a deprecated version of this API.",
            DeprecationDate: time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC),
            DeprecationInfo: "A newer version is available.",
        },
        Versions: versioning.Versions{
            {
                Range:      ">=1.0.0 <2.0.0",
                Path:       "/v1",
                Deprecated: true,
            },
            {
                Range: ">=2.0.0",
                Path:  "/v2",
            },
        },
    }

    versioningMiddleware := versioning.New(opts)
    app.UseRouter(versioningMiddleware)

    v1 := app.Router("/v1")
    {
        v1.Get("/", func(ctx iris.Context) {
            ctx.WriteString("Hello from version 1")
        })
    }

    v2 := app.Router("/v2")
    {
        v2.Get("/", func(ctx iris.Context) {
            ctx.WriteString("Hello from version 2")
        })
    }

    app.Listen(":8080")
}

Documentation

Overview

Package versioning routes a request to a handler by the API version it asks for, through the Accept-Version header, the Accept header or a custom source.

Its entry point is New(Options), which returns a Handler that matches a version to one of the registered handlers. See also `NewMatcher` and the `Deprecated` helper.

Index

Constants

View Source
const (
	// AcceptVersionHeaderKey is the header key of "Accept-Version".
	AcceptVersionHeaderKey = "Accept-Version"
	// AcceptHeaderKey is the header key of "Accept".
	AcceptHeaderKey = "Accept"
)
View Source
const (
	APIWarnHeader            = "X-Api-Warn"
	APIDeprecationDateHeader = "X-Api-Deprecation-Date"
	APIDeprecationInfoHeader = "X-Api-Deprecation-Info"
)

The response header keys when a resource is deprecated by the server.

Variables

View Source
var DefaultDeprecationOptions = DeprecationOptions{
	WarnMessage: "WARNING! You are using a deprecated version of this API.",
}

DefaultDeprecationOptions are the default deprecation options, it defaults the "X-API-Warn" header to a generic message.

View Source
var DefaultNotFoundHandler = func(ctx *context.Context) {
	ctx.StopWithError(501, ErrNotFound)
}

DefaultNotFoundHandler is the default version not found handler. It returns a 501 Not Implemented status code.

View Source
var ErrNotFound = errors.New("version not found")

ErrNotFound is returned when a version is not found.

Functions

func Get

func Get(ctx *context.Context) string

Get returns the version constraint from the context.

func New

func New(opts Options) context.Handler

New returns a new versioning router handler. Register it through the `app.UseRouter` method. It matches the request version with the provided versions. If the version is not found, the not found handler is called. If the version is deprecated, the deprecation headers are written to the response. If the version is "latest" then the latest provided version is used. If the version is not provided at all and the strict mode is enabled, the not found handler is called, otherwise it continues to the router. If no versions are provided, all versions are matched with the default path pattern. The default pattern is: "/v$VERSION_MAJOR/$REQUEST_PATH". Usage:

ver := versioning.New(versioning.Options{
	Default: "1.0.0",
	Latest: "2.0.0",
	Strict: false,
	Header: "Accept-Version",
	QueryParam: "v",
	Subdomain: false,
	NotFoundHandler: func(ctx iris.Context) {...},
	Skipper: func(ctx iris.Context) bool { ...},
	Deprecation: versioning.DeprecationOptions{
		WarnMessage: "WARNING! You are using a deprecated version of this API.",
		DeprecationDate: time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC),
		DeprecationInfo: "",
	},
	Versions: versioning.Versions{
		{
			Range:      ">=1.0.0 <2.0.0",
			Path:       "/v1", // or, the same effect by using pattern: "/v$1/$4" to redirect to the same path but with the version prefix.
			Deprecated: false,
		},
	},
})
app.UseRouter(ver)

func WithNotFoundHandler

func WithNotFoundHandler(handler context.Handler) context.Handler

WithNotFoundHandler sets the version not found handler to the context. Can be useful to customize the not found handler per route or per group of routes.

Types

type DeprecationOptions

type DeprecationOptions struct {
	WarnMessage     string    `json:"warn_message" yaml:"WarnMessage"`
	DeprecationDate time.Time `json:"deprecation_date" yaml:"DeprecationDate"`
	DeprecationInfo string    `json:"deprecation_info" yaml:"DeprecationInfo"`
}

DeprecationOptions describes the deprecation headers key-values. - "X-Api-Warn": options.WarnMessage - "X-Api-Deprecation-Date": options.DeprecationDate.Format(http.TimeFormat) - "X-Api-Deprecation-Info": options.DeprecationInfo

func (*DeprecationOptions) Headers

func (opts *DeprecationOptions) Headers() http.Header

Headers returns the deprecation headers based on the options.

func (DeprecationOptions) ShouldHandle

func (opts DeprecationOptions) ShouldHandle() bool

ShouldHandle reports whether the deprecation headers should be present or no.

func (*DeprecationOptions) WriteTo

func (opts *DeprecationOptions) WriteTo(w http.ResponseWriter)

WriteTo writes the deprecation headers to the response writer.

type Options

type Options struct {
	// Default is the default version. It is optional.
	// Defaults to the Latest value when Latest is provided, otherwise it stays empty,
	// which intentionally disables the version matching for requests without a version.
	// In strict mode it is always cleared.
	Default string `json:"default" yaml:"Default"`
	// Latest is the latest version. It is optional.
	// If provided, the client can request for the latest version by using the "latest" value.
	// E.g Latest: "3.0.0".
	Latest string `json:"latest" yaml:"Latest"`
	// Strict is the strict mode. It is optional.
	// If true, the Default field has no effect, and the client must request for a specific version, otherwise the router will not be called.
	Strict bool `json:"strict" yaml:"Strict"`

	// Versions is the list of versions. It is optional.
	// The order of the versions matters.
	// The first version that matches the request version is used.
	// If no version matches the request version, the request is not found.
	// If a version is deprecated, the deprecation headers are written to the response.
	//
	// If no provided then all versions will be redirected to the default path pattern which is: "/v$VERSION_MAJOR/$REQUEST_PATH".
	Versions Versions `json:"versions" yaml:"Versions"`

	// Deprecation is the deprecation options. It is optional.
	Deprecation DeprecationOptions `json:"deprecation" yaml:"Deprecation"`
	// Header is the version header key. It is optional.
	// Defaults to "Accept-Version".
	Header string `json:"header" yaml:"Header"`
	// QueryParam is the version query parameter key. It is optional.
	// Defaults to "v".
	QueryParam string `json:"query_param" yaml:"QueryParam"`

	// Subdomain specifies if the framework should lookup subdomain for a version, the form of it should be "v1" ("v" + digit). It is optional.
	// Defaults to false.
	Subdomain bool `json:"subdomain" yaml:"Subdomain"`

	// NotFoundHandler is the version not found handler. It is optional.
	// Defaults to DefaultNotFoundHandler (501 Not Implemented with ErrNotFound).
	NotFoundHandler context.Handler `json:"-" yaml:"-"`
	// Skipper is a function which if it's provided it can report whether the versioning middleware
	// runs or not on specific requests (e.g. by path prefix). It is optional.
	// If it returns true then the versioning middleware must not run.
	// Defaults to nil.
	// Usage:
	// versioning.Options{
	// 	Skipper: func(ctx iris.Context) bool {
	// 		return !strings.HasPrefix(ctx.Path(), "/api")
	// 	},
	// }
	Skipper func(*context.Context) bool `json:"-" yaml:"-"`
}

Options is the versioning handler options.

type Skipper

type Skipper = func(ctx *context.Context) bool

Skipper is a function which reports whether the versioning middleware should run or not on specific requests. It can be used to skip the versioning middleware on specific requests (e.g. by path prefix). If it returns true then the versioning middleware must not run. Usage:

versioning.Options{
	Skipper: func(ctx iris.Context) bool {
		return !strings.HasPrefix(ctx.Path(), "/api")
	},
}

See `OnlyPath` and `OnlyAPI` for ready-to-use Skipper functions.

var (
	// OnlyAPI is a helper function which can be used as a Skipper to run the versioning middleware only on specific requests by the "/api" path prefix.
	// Usage:
	//
	//	versioning.Options{
	//		Skipper: versioning.OnlyAPI,
	//	    [...]
	//	}
	OnlyAPI Skipper = OnlyPath("/api")
	// OnlyPath is a helper function which can be used as a Skipper to run the versioning middleware only on specific requests by the path prefix.
	// Usage:
	//
	//	versioning.Options{
	//		Skipper: versioning.OnlyPath("/api"),
	//		[...]
	OnlyPath = func(pathPrefix string) Skipper {
		return func(ctx *context.Context) bool {
			path := ctx.Request().URL.Path

			if after, ok := strings.CutPrefix(path, pathPrefix); ok {
				ctx.Request().URL.Path = after
				return false
			}

			return true

		}
	}
)

type Version

type Version struct {
	Range      string `json:"range" yaml:"Range"`
	Path       string `json:"path" yaml:"Path"`
	Deprecated bool   `json:"deprecated" yaml:"Deprecated"`
}

Version describes a version and the redirect path. It is used to match the request version with the provided version range. If the version is found, the request path is redirected to the provided path pattern.

type Versions

type Versions = []Version

Versions is a list of versions.

Jump to

Keyboard shortcuts

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