prefixhandler

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2018 License: MIT Imports: 3 Imported by: 0

README

prefixhandler

Build Status Coverage Status Go Report Card GoDoc

Path Prefix Handler for http.ServeMux

Example

package main

import (
    "io"
    "net/http"

    "github.com/acoshift/prefixhandler"
)

func main() {
    mux := http.NewServeMux()

    itemMux := http.NewServeMux()
    itemMux.Handle("/", http.HandlerFunc(itemDetail))
    itemMux.Handle("/edit", http.HandlerFunc(itemEdit))

    mux.Handle("/item", http.NotFoundHandler())
    mux.Handle("/item/", prefixhandler.New("/item", "item_id", itemMux))

    http.ListenAndServe(":8080", mux)
}

func itemDetail(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        http.NotFound(w, r)
        return
    }

    itemID := prefixhandler.Get(r.Context(), "item_id")
    // or
    // itemID = r.Context().Value("item_id").(string)

    if itemID == "" {
        http.NotFound(w, r)
        return
    }

    io.WriteString(w, "Item: "+itemID)
}

func itemEdit(w http.ResponseWriter, r *http.Request) {
    itemID := prefixhandler.Get(r.Context(), "item_id")
    io.WriteString(w, "Editing Item: "+itemID)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(ctx context.Context, ctxKey interface{}) string

Get gets prefix from context key

func New

func New(prefix string, ctxKey interface{}, h http.Handler) http.Handler

New creates new prefix handler

Types

This section is empty.

Jump to

Keyboard shortcuts

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