mux

package module
v0.2.1-0...-d84ba5b Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2022 License: ISC Imports: 7 Imported by: 0

README

Go Reference

Mux

A golang HTTP request multiplexer.

Install

go get github.com/nicolasparada/go-router

Usage

Simple: familiar API using http.Handler and http.HandlerFunc interfaces.

func main() {
  r := mux.NewRouter()
  r.Handle("/test", test)

  http.ListenAndServe(":5000", r)
}

URL param: capture URL parameters with {myParam} notation, and access them with mux.URLParam(ctx, "myParam").

func main() {
  r := mux.NewRouter()
  r.HandleFunc("/hello/{name}", hello)

  http.ListenAndServe(":5000", r)
}

func hello(w http.ResponseWriter, r *http.Request) {
    name := mux.URLParam(r.Context(), "name")
    fmt.Fprintf(w, "Hello, %s", name)
}

Wildcard: match anything with *.

func main() {
  r := mux.NewRouter()
  r.Handle("/*", http.FileServer(http.FS(static)))

  http.ListenAndServe(":5000", r)
}

REST: mux by HTTP method using mux.MethodHandler. It will respond with 405 Method Not Allowed for you if none match.

func main() {
  r := mux.NewRouter()
  r.Handle("/api/todos", mux.MethodHandler{
    http.MethodPost: createTodo,
    http.MethodGet:  todos,
  })
  r.Handle("/api/todos/{todoID}", mux.MethodHandler{
    http.MethodGet:    todo,
    http.MethodPatch:  updateTodo,
    http.MethodDelete: deleteTodo,
  })

  http.ListenAndServe(":5000", r)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func URLParam

func URLParam(ctx context.Context, name string) string

URLParam extracts an URL parameter previously defined in the URL pattern.

Types

type MethodHandler

type MethodHandler map[string]http.HandlerFunc

MethodHandler maps each handler to the corresponding method. Responds with "method not allowed" if none match.

func (MethodHandler) ServeHTTP

func (mh MethodHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches the request to the handler whose method matches, otherwise it responds with "method not allowed".

type Router

type Router struct {
	NotFoundHandler http.Handler
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() *Router

NewRouter returns a new Router.

func (*Router) Handle

func (mux *Router) Handle(pattern string, handler http.Handler)

Handle registers a handler for the given pattern.

func (*Router) HandleFunc

func (mux *Router) HandleFunc(pattern string, handler http.HandlerFunc)

Handle registers a handler function for the given pattern.

func (*Router) ServeHTTP

func (mux *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches the request to the handler whose pattern matches, otherwise it responds with "not found".

Jump to

Keyboard shortcuts

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