rewrite

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: 13 Imported by: 0

README

Rewrite Middleware for Iris

This middleware matches an incoming URL against your rules and rewrites or redirects it. Use it when paths change and old links must keep working, when you want one canonical subdomain, or when short URLs should expand into real routes.

Features of Iris Rewrite Middleware

The Iris rewrite middleware offers a variety of features to handle URL rewriting efficiently. These features include:

  1. Redirect Match: Allows defining redirection rules using regular expressions.
  2. Primary Subdomain Redirection: Automatically redirects root domain requests to a specified primary subdomain.
  3. Customizable Options: Provides options to customize the rewrite rules and behavior.
  4. Support for Various File Formats: Supports loading rewrite rules from JSON and YAML files.
  5. Debugging: Provides logging capabilities for debugging rewrite rules.

Installation

To use the Iris rewrite middleware, you need to import it in your Iris application:

import "github.com/kataras/iris/v14/middleware/rewrite"

Usage

Basic Setup

To use the rewrite middleware, you need to import the necessary packages and configure the middleware in your Iris application. Here is a basic example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/middleware/rewrite"
)

func main() {
	app := iris.New()
	opts := rewrite.Options{
		RedirectMatch: []string{
			"301 /old-path /new-path",
		},
	}
	engine, err := rewrite.New(opts)
	if err != nil {
		panic(err)
	}
	// Or, to panic on a bad rule in one line:
	//	engine := rewrite.Must(opts)
	app.UseRouter(engine.Handler)

	app.Get("/new-path", func(ctx iris.Context) {
		ctx.WriteString("New Path")
	})

	app.Listen(":8080")
}
Redirect Match

The rewrite middleware allows defining redirection rules using regular expressions. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/middleware/rewrite"
)

func main() {
	app := iris.New()
	opts := rewrite.Options{
		RedirectMatch: []string{
			"301 /old-path/(.*) /new-path/$1",
		},
	}
	engine, err := rewrite.New(opts)
	if err != nil {
		panic(err)
	}
	app.UseRouter(engine.Handler)

	app.Get("/new-path/{param}", func(ctx iris.Context) {
		param := ctx.Params().Get("param")
		ctx.Writef("New Path with param: %s", param)
	})

	app.Listen(":8080")
}
Primary Subdomain Redirection

The rewrite middleware can automatically redirect root domain requests to a specified primary subdomain. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/middleware/rewrite"
)

func main() {
	app := iris.New()
	opts := rewrite.Options{
		PrimarySubdomain: "www",
	}
	engine, err := rewrite.New(opts)
	if err != nil {
		panic(err)
	}
	app.UseRouter(engine.Handler)

	app.Get("/", func(ctx iris.Context) {
		ctx.WriteString("Root Domain")
	})

	app.Listen(":8080")
}
Loading Rewrite Rules from Files

The rewrite middleware supports loading rewrite rules from JSON and YAML files. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/middleware/rewrite"
)

func main() {
	app := iris.New()
	engine := rewrite.Load("redirects.yml")
	app.UseRouter(engine)

	app.Get("/new-path", func(ctx iris.Context) {
		ctx.WriteString("New Path")
	})

	app.Listen(":8080")
}

The redirects.yml file should contain the rewrite rules in YAML format:

RedirectMatch: # REDIRECT_CODE_DIGITS | PATTERN_REGEX | TARGET_REPL
  # Redirects /seo/* to /*
  - 301 /seo/(.*) /$1

  # Redirects /docs/v14* to /docs
  - 301 /docs/v14(.*) /docs

  # Redirects /old(.*) to /
  - 301 /old(.*) /

  # Redirects http or https://test.* to http or https://newtest.*
  - 301 ^(http|https)://test.(.*) $1://newtest.$2

  # Handles /*.json or .xml as *?format=json or xml,
  # WITHOUT redirect. See /users route.
  # When Code is 0 then it does not redirect the request,
  # instead it changes the request URL
  # and leaves a route handle the request.
  - 0 /(.*).(json|xml) /$1?format=$2

# Redirects root domain to www.
# Creation of a www subdomain inside the Application is unnecessary,
# all requests are handled by the root Application itself.
PrimarySubdomain: www
Debugging

The rewrite middleware provides logging capabilities for debugging rewrite rules. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/middleware/rewrite"

	"github.com/kataras/golog"
)

func main() {
	app := iris.New()
	opts := rewrite.Options{
		RedirectMatch: []string{
			"301 /old-path /new-path",
		},
	}
	engine, err := rewrite.New(opts)
	if err != nil {
		panic(err)
	}

    golog.SetLevel("debug")
	engine.SetLogger(golog.Default)

	app.UseRouter(engine.Handler)

	app.Get("/new-path", func(ctx iris.Context) {
		ctx.WriteString("New Path")
	})

	app.Listen(":8080")
}

Documentation

Overview

Package rewrite redirects or rewrites requests according to a list of regular-expression rules, and can force a primary subdomain such as "www".

Its entry point is New(Options), which returns an *Engine rather than a Handler because the engine is also a router wrapper with its own logger: register its `Handler` method with Application.UseRouter. Use `Must` to panic on a bad rule instead of reporting it, or `Load` to read the rules from a YAML or JSON file.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load(filename string) context.Handler

Load decodes the "filename" options and returns a new Rewrite Engine Router Middleware. It panics on errors. Usage: redirects := Load("redirects.yml") app.UseRouter(redirects) See `New` too.

Types

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is a struct that represents a rewrite engine for Iris web framework. It contains a slice of redirect rules, an options struct, a logger, and a domain validator function. It provides methods to create, configure, and apply rewrite rules to HTTP requests and responses.

func Must

func Must(opts Options) *Engine

Must is New but it panics on a parser error. Usage:

engine := rewrite.Must(rewrite.Options{RedirectMatch: []string{"301 /seo/(.*) /$1"}})
app.UseRouter(engine.Handler)

func New

func New(opts Options) (*Engine, error)

New returns a new Rewrite Engine based on "opts". It reports any parser error. See its `Handler` method and the `Must` companion.

func (*Engine) Handler

func (e *Engine) Handler(ctx *context.Context)

Handler is a router middleware, it is used to wrap the entire Iris Router to apply the given rewrite rules.

Usage: app.UseRouter(engine.Handler).

func (*Engine) SetLogger

func (e *Engine) SetLogger(logger *golog.Logger) *Engine

SetLogger attachs a logger to the Rewrite Engine, used only for debugging. Defaults to nil.

type Options

type Options struct {
	// RedirectMatch accepts a slice of lines
	// of form:
	// REDIRECT_CODE PATH_PATTERN TARGET_PATH
	// Example: []{"301 /seo/(.*) /$1"}.
	RedirectMatch []string `json:"redirectMatch" yaml:"RedirectMatch"`

	// Root domain requests redirect automatically to primary subdomain.
	// Example: "www" to redirect always to www.
	// Note that you SHOULD NOT create a www subdomain inside the Iris Application.
	// This field takes care of it for you, the root application instance
	// will be used to serve the requests.
	PrimarySubdomain string `json:"primarySubdomain" yaml:"PrimarySubdomain"`
}

Options holds the developer input to customize the redirects for the Rewrite Engine. Look the `New` and `Load` package-level functions.

func LoadOptions

func LoadOptions(filename string) (opts Options)

LoadOptions loads rewrite Options from a system file.

Jump to

Keyboard shortcuts

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