mux

package
v0.0.97 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2024 License: MIT Imports: 5 Imported by: 1

Documentation

Overview

Package mux implements a HTTP request multiplexer.

Index

Examples

Constants

View Source
const (
	MethodAll     = mx.MethodAll
	MethodGet     = mx.MethodGet
	MethodHead    = mx.MethodHead
	MethodPost    = mx.MethodPost
	MethodPut     = mx.MethodPut
	MethodPatch   = mx.MethodPatch
	MethodDelete  = mx.MethodDelete
	MethodConnect = mx.MethodConnect
	MethodOptions = mx.MethodOptions
	MethodTrace   = mx.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 Muxer added in v0.0.77

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

Muxer 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 Muxer.

Example
package main

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

	"github.com/komuw/ong/config"
	"github.com/komuw/ong/log"
	"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(context.Background(), os.Stdout, 1000)
	mx := mux.New(
		config.WithOpts("localhost", 8080, "super-h@rd-Pas1word", config.DirectIpStrategy, l),
		nil,
		mux.NewRoute(
			"login/",
			mux.MethodGet,
			LoginHandler(),
		),
		mux.NewRoute(
			"/books/:author",
			mux.MethodAll,
			BooksByAuthorHandler(),
		),
	)

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

func New

func New(opt config.Opts, notFoundHandler http.Handler, routes ...Route) Muxer

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 (Muxer) GoString added in v0.0.77

func (m Muxer) GoString() string

GoString implements fmt.GoStringer

func (Muxer) Resolve added in v0.0.77

func (m Muxer) 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/config"
	"github.com/komuw/ong/log"
	"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(context.Background(), os.Stdout, 1000)
	mx := mux.New(
		config.WithOpts("localhost", 8080, "super-h@rd-Pas1word", config.DirectIpStrategy, l),
		nil,
		mux.NewRoute(
			"login/",
			mux.MethodGet,
			LoginHandler(),
		),
		mux.NewRoute(
			"/books/:author",
			mux.MethodAll,
			BooksByAuthorHandler(),
		),
	)

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

func (Muxer) ServeHTTP added in v0.0.77

func (m Muxer) 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.

func (Muxer) String added in v0.0.77

func (m Muxer) String() string

String implements fmt.Stringer

func (Muxer) Unwrap added in v0.0.77

func (m Muxer) Unwrap() mx.Muxer

Unwrap returns the underlying muxer. It is for internal use(ONLY) by ong. Users of ong should not need to call it.

type Route added in v0.0.14

type Route = mx.Route

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

Jump to

Keyboard shortcuts

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