methodmux

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2018 License: MIT Imports: 2 Imported by: 1

README

methodmux

Build Status Coverage Status Go Report Card GoDoc

Method Multiplexer for http.ServeMux

Example

package main

import (
    "io"
    "net/http"

    "github.com/acoshift/methodmux"
)

func main() {
    mux := http.NewServeMux()
    mux.Handle("/", methodmux.Get(http.HandlerFunc(index)))
    mux.Handle("/about", methodmux.Mux{
        http.MethodGet:  http.HandlerFunc(aboutGet),
        http.MethodPost: http.HandlerFunc(aboutPost),
        "":              http.HandlerFunc(aboutOther),
    })
    http.ListenAndServe(":8080", mux)
}

func index(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello, Method Mux!")
}

func aboutGet(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "About Get")
}

func aboutPost(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "About Post")
}

func aboutOther(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "About does not support method "+r.Method)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FallbackHandler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	m := GetMux(r.Context())
	for method := range m {
		if method != "" {
			w.Header().Add("Allow", method)
		}
	}
	http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
})

FallbackHandler is the default fallback handler if no method matched

Functions

This section is empty.

Types

type Mux

type Mux map[string]http.Handler

Mux is the method mux

func Delete

func Delete(h http.Handler) Mux

Delete is a short-hand for Mux{http.MethodDelete: h}

func Get

func Get(h http.Handler) Mux

Get is a short-hand for Mux{http.MethodGet: h}

func GetMux added in v1.1.0

func GetMux(ctx context.Context) Mux

GetMux gets mux from request's context only for fallback handler

func GetPost

func GetPost(get, post http.Handler) Mux

GetPost is a short-hand for Mux{http.MethodGet: get, http.MethodPost: post}

func Head(h http.Handler) Mux

Head is a short-hand for Mux{http.MethodHead: h}

func Options

func Options(h http.Handler) Mux

Options is a short-hand for Mux{http.MethodOptions: h}

func Patch

func Patch(h http.Handler) Mux

Patch is a short-hand for Mux{http.MethodPatch: h}

func Post

func Post(h http.Handler) Mux

Post is a short-hand for Mux{http.MethodPost: h}

func Put

func Put(h http.Handler) Mux

Put is a short-hand for Mux{http.MethodPut: h}

func (Mux) ServeHTTP

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

Jump to

Keyboard shortcuts

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