Usage of nested Handlers

Idea

  • Register a RESTful API for customers

Example

Use the nested multiplexer

  • NestedMux wraps several business logic handlers
  • ServeMux wraps the NestedMux and serves all requests
package main

import (
    "net/http"

    "./pkg/httpx"
    "./pkg/customers"
)

const (
    // Prefix for API calls.
    apiPrefix = "/api/v1"
)

func main() { 
    mux := http.NewServeMux()
    apimux := httpx.NewNestedMux(apiPrefix)

    apimux.Handle("customers", httpx.MethodWrapper(customers.NewHandler()))
    apimux.Handle("customers/addresses", httpx.MethodWrapper(customers.NewAddressesHandler()))
    apimux.Handle("customers/contracts", httpx.MethodWrapper(customers.NewContractsHandler()))

    // Register further nested API handlers, then
    // let the multiplexer serve all API requests.

    mux.Handle(apiPrefix, apimux)

    // Register further multiplexed handlers, e.g. for static files.

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