mux

package
v0.0.57-rc.27 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2023 License: MIT Imports: 11 Imported by: 1

Documentation

Overview

Package mux implements a HTTP request multiplexer.

Index

Examples

Constants

View Source
const (
	MethodAll     = "ALL"
	MethodGet     = http.MethodGet
	MethodHead    = http.MethodHead
	MethodPost    = http.MethodPost
	MethodPut     = http.MethodPut
	MethodPatch   = http.MethodPatch
	MethodDelete  = http.MethodDelete
	MethodConnect = http.MethodConnect
	MethodOptions = http.MethodOptions
	MethodTrace   = http.MethodTrace
)

Common HTTP methods.

Variables

This section is empty.

Functions

func Param

func Param(ctx context.Context, param string) string

Param gets the path/url parameter from the specified Context. It returns an empty string if the parameter was not found.

Types

type Mux

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

Mux is a HTTP request multiplexer.

It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL. It implements http.Handler

Use New to get a valid Mux.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"

	"github.com/komuw/ong/log"
	"github.com/komuw/ong/middleware"
	"github.com/komuw/ong/mux"
)

func LoginHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		_, _ = fmt.Fprint(w, "welcome to your favorite website.")
	}
}

func BooksByAuthorHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		author := mux.Param(r.Context(), "author")
		_, _ = fmt.Fprintf(w, "fetching books by author: %s", author)
	}
}

func main() {
	l := log.New(os.Stdout, 1000)(context.Background())
	mux := mux.New(
		l,
		middleware.WithOpts("localhost", 8080, "secretKey", middleware.DirectIpStrategy, l),
		nil,
		mux.NewRoute(
			"login/",
			mux.MethodGet,
			LoginHandler(),
		),
		mux.NewRoute(
			"/books/:author",
			mux.MethodAll,
			BooksByAuthorHandler(),
		),
	)

	server := &http.Server{
		Handler: mux,
		Addr:    ":8080",
	}
	err := server.ListenAndServe()
	if err != nil {
		panic(err)
	}
}
Output:

func New

func New(l *slog.Logger, opt middleware.Opts, notFoundHandler http.Handler, routes ...Route) Mux

New returns a HTTP request multiplexer that has the paths in routes.

notFoundHandler is the handler that will be used if a url is not found. If it is nil, http.NotFound is used instead.

All the paths of an application should be added as part of the routes slice argument. Typically, an application should only have one Mux.

It panics with a helpful error message if it detects conflicting routes.

func (Mux) Resolve added in v0.0.49

func (m Mux) Resolve(path string) Route

Resolve resolves a URL path to its corresponding Route and hence http handler. If no corresponding route/handler is found, a zero value Route is returned.

It is not intended for use in production settings, it is more of a dev/debugging tool. It is inspired by django's resolve url utility.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"

	"github.com/komuw/ong/log"
	"github.com/komuw/ong/middleware"
	"github.com/komuw/ong/mux"
)

func LoginHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		_, _ = fmt.Fprint(w, "welcome to your favorite website.")
	}
}

func BooksByAuthorHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		author := mux.Param(r.Context(), "author")
		_, _ = fmt.Fprintf(w, "fetching books by author: %s", author)
	}
}

func main() {
	l := log.New(os.Stdout, 1000)(context.Background())
	mux := mux.New(
		l,
		middleware.WithOpts("localhost", 8080, "secretKey", middleware.DirectIpStrategy, l),
		nil,
		mux.NewRoute(
			"login/",
			mux.MethodGet,
			LoginHandler(),
		),
		mux.NewRoute(
			"/books/:author",
			mux.MethodAll,
			BooksByAuthorHandler(),
		),
	)

	fmt.Println(mux.Resolve("nonExistentPath"))
	fmt.Println(mux.Resolve("login/"))
	fmt.Println(mux.Resolve("https://localhost/books/SidneySheldon"))
}
Output:

func (Mux) ServeHTTP

func (m Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements a http.Handler

It routes incoming http requests based on method and path extracting path parameters as it goes.

type Route added in v0.0.14

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

Route represents the pattern & http method that will be served by a particular http handler.

Use NewRoute to get a valid Route.

func NewRoute

func NewRoute(
	pattern string,
	method string,
	handler http.Handler,
) Route

NewRoute creates a new Route.

It panics if handler has already been wrapped with ong/middleware

func (Route) String added in v0.0.14

func (r Route) String() string

Jump to

Keyboard shortcuts

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