rewrite

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2022 License: MIT Imports: 12 Imported by: 0

README

Rewrite

build status report card godocs

Like Apache mod_rewrite but for Golang's net/http. Initially created for the Iris Web Framework a long time ago. The success of its usefulness is well known as many others have copied and moved the original source code into various frameworks since then, if you deem it necessary, you are free to do the same.

Installation

The only requirement is the Go Programming Language.

$ go get github.com/kataras/rewrite
Examples

Getting Started

The Rewrite Middleware supports rewrite URL path, subdomain or host based on a regular expression search and replace.

The syntax is familiar to the majority of the backend developers out there and it looks like that:

REDIRECT_CODE_DIGITS PATTERN_REGEX TARGET_REPL
301 /seo/(.*) /$1

Would redirect all requests from relative path /seo/* to /* using the 301 (Moved Permanently) HTTP Status Code. Learn more about regex.

Usage

First of all, you should import the builtin middleware as follows:

import "github.com/kataras/rewrite"

There are two ways to load rewrite options in order to parse and register the redirect rules:

1. Through code using the New function and Handler method. Parse errors can be handled and rules can be programmatically created.

// 1. Code the redirect rules.
opts := rewrite.Options{
	RedirectMatch: []string{
		"301 /seo/(.*) /$1",
		"301 /docs/v12(.*) /docs",
		"301 /old(.*) /",
	},
	PrimarySubdomain: "www",
}
// 2. Initialize the Rewrite Engine.
rw, err := rewrite.New(opts)
if err != nil { 
	panic(err)
}

// 3. Wrap the router using Engine's Handler method.
http.ListenAndServe(":8080", rw.Handler(mux))

2. Or through a yaml file using the Load function which returns a func(http.Handler) http.Handler. It is the most common scenario and the simplest one. It panics on parse errors.

The "redirects.yml" file looks like that:

RedirectMatch:
  # Redirects /seo/* to /*
  - 301 /seo/(.*) /$1

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

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

# Redirects root domain requests to www.
PrimarySubdomain: www
func main() {
    mux := http.NewServeMux()
    // [...routes]
	redirects := rewrite.Load("redirects.yml")
	// Wrap the router.
    http.ListenAndServe(":8080", redirects(mux))
}

Example

Let's write a simple application which follows the redirect rules of:

SOURCE TARGET
http://localhost:8080/seo/about http://localhost:8080/about
http://mydomain.com:8080/docs/v12/hello http://www.mydomain.com:8080/docs
http://mydomain.com:8080/docs/v12some http://www.mydomain.com:8080/docs
http://mydomain.com:8080/oldsome http://www.mydomain.com:8080
http://mydomain.com:8080/oldindex/random http://www.mydomain.com:8080
Server
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/kataras/rewrite"
)

func main() {
	// Code the redirect rules.
	opts := rewrite.Options{
		RedirectMatch: []string{
			"301 /seo/(.*) /$1",       // redirect /seo/* to /*
			"301 /docs/v12(.*) /docs", // redirect docs/v12/* to /docs
			"301 /old(.*) /",          // redirect /old** to /
		},
		PrimarySubdomain: "www", // redirect root to www. subdomain.
	}
	// Initialize the Rewrite Engine.
	rw, err := rewrite.New(opts)
	if err != nil {
		log.Fatal(err)
	}

	router := http.NewServeMux()
	router.HandleFunc("/", index)
	router.HandleFunc("/about", about)
	router.HandleFunc("/docs", docs)

	log.Println("Listening on :8080")
	// Wrap the router using the Handler method.
	http.ListenAndServe(":8080", rw.Handler(router))
}

func index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Index")
}

func about(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "About")
}

func docs(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Docs")
}
Hosts File
127.0.0.1	mydomain.com
127.0.0.1	www.mydomain.com

Navigate here if you don't know how to modify the system's hosts file.

License

This software is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load(filename string) func(http.Handler) http.Handler

Load decodes the "filename" options and returns a new Rewrite Engine http.Handler wrapper that can be used as a middleware. It panics on errors.

Usage:

redirects := Load("redirects.yml")
http.ListenAndServe(":8080", redirects(router))

See `New` package-level function too.

Types

type Engine

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

Engine is the rewrite engine main structure. Navigate through https://github.com/kataras/rewrite/tree/main/_examples for more.

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 to register it on an application.

func (*Engine) Handler

func (e *Engine) Handler(next http.Handler) http.Handler

Handler is the main Engine's method. It is http.Handler wrapper that should be registered at the top of the http application server. Usage:

http.ListenAndServe(":8080", rw.Handler(router))

func (*Engine) SetLogger

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

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

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"`

	// Debug to enable debug log.Printf messages.
	Debug bool `json:"debug" yaml:"Debug"`
}

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

func LoadOptions

func LoadOptions(filename string) (Options, error)

LoadOptions loads rewrite Options from a system file.

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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