Skip to content

httpmock: programmable-router

Back to gallery

Exhibit path: docs/examples/codegen/httpmock/programmable-router/

A router with multiple routes registered at test setup. Shows the standard httpmock pattern: annotate the transport interface, generate the scaffold, register handlers in the test.

Input (in.go)

go
//go:build glacier_codegen_fixture

// Package apiclient defines the HTTP transport for the API client.
package apiclient

import "net/http"

// Transport is the HTTP transport interface used by the API client.
//
// +glacier:mock
type Transport interface {
	// RoundTrip executes an HTTP request.
	RoundTrip(req *http.Request) (*http.Response, error)
}

Output (out.go)

go
//go:build glacier_codegen_fixture

// Code generated by glaciergen. DO NOT EDIT.
// Source: in.go
package apiclient

import (
	"net/http"

	"github.com/nathanbrophy/glacier/httpmock"
)

// MockTransport is a generated httpmock-backed transport for Transport.
type MockTransport struct {
	router *httpmock.Router
}

// NewMockTransport returns a MockTransport with an empty route table.
// Register routes with mock.Route before making requests.
func NewMockTransport() *MockTransport {
	return &MockTransport{router: httpmock.NewRouter()}
}

// Route registers a handler for the given method and path pattern.
func (m *MockTransport) Route(method, path string, handler httpmock.Handler) {
	m.router.Route(method, path, handler)
}

// RoundTrip implements Transport (and http.RoundTripper).
func (m *MockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	return m.router.RoundTrip(req)
}

What the generator did

  • Found the +glacier:mock marker on the HTTP transport interface.
  • Generated a MockTransport that implements http.RoundTripper.
  • The generated Router field accepts route registrations (GET /users, POST /users, etc.) at test-setup time.
  • Unregistered routes return a 404 by default, making accidental real-HTTP calls visible immediately.

recording-disabled with-body-closure glacier generate

Apache-2.0