liveBook · Manning

Method-based subrouting

As explained in Go in Practice, Second Edition

Method-based subrouting is routing that selects request logic by HTTP method after a shared top-level path has been matched.

Method-based subrouting matches a shared path and selects request logic by HTTP method. In Go, register separate handlers such as GET /comments and POST /comments with net/http. section 8.1.1

Comments endpoint

A comments endpoint can serve existing comments with GET and append a submitted comment with POST. Requests using another method receive 405 Method Not Allowed; curl can exercise the POST route. section 8.1.1

Listing 8.1 Using built-in method routing
package main

import (
    "net/http"
)

func getComments(w http.ResponseWriter, 
r *http.Request) {                        #1
    w.Write([]byte("here you'll get the comments"))
}

func postComments(w http.ResponseWriter, 
r *http.Request) {                      #2
    w.Write([]byte("thank you for posting a comment"))
}

func main() {
    http.HandleFunc("GET /comments", getComments)     #3
    http.HandleFunc("POST /comments", postComments)              #4
    if err := http.ListenAndServe(":8000", nil); err != nil {
        panic(err)
    }
}

Use the complete net/http example to register distinct GET and POST handlers for the same /comments path and run the server on port 8000. section 8.1.1

Manual dispatch remains useful when method handling needs additional decisions:

  • Inspect r.Method, read and decode a POST body, then choose creation or update logic based on the decoded identifier. section 8.1.1
  • Consider OPTIONS responses when an endpoint should advertise its supported methods, and return explanatory error text where useful. section 8.1.1

How Go in Practice, Second Edition covers it

How deep it goes
Explains built-in registrations, exercised requests, 405 handling, and manual dispatch, while deferring broader REST architecture.
Examples
Uses a comments endpoint, curl POST request, in-memory comments, and a JSON-based upsert handler.
What it assumes
Assumes basic Go HTTP handler knowledge and develops method routing through concrete net/http examples.
What you can do after
Apply it via Go net/http to build method-specific handlers and manually dispatch more complex endpoint logic.
How it connects
Connects HTTP methods, REST, status codes, OPTIONS, request bodies, JSON decoding, and upsert endpoints.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.