Package and API Design
What you will learn
By the end of this lesson, you will be able to:
- define a package around one coherent responsibility;
- make useful zero values and invariants explicit;
- choose constructors, options, interfaces, and concrete types deliberately;
- design context and error contracts;
- evolve an exported API without surprising callers.
A package is a unit of understanding
A good package lets a reader answer:
- What does it provide?
- What does it own?
- What must the caller provide or release?
- Is it safe for concurrent use?
- How does it fail?
- Which parts are stable public contracts?
Package boundaries should follow responsibility and change, not arbitrary layer counts.
Name from the caller's perspective
Package names are short, lowercase, and avoid repetition:
lesson.Create(...) // clearer
lesson.NewLesson(...) // often repetitive
Avoid generic buckets such as util, common, base, or helpers. A function named util.Parse gives little clue about its domain or ownership.
Design a useful zero value
When practical, make the zero value ready to use:
var buffer bytes.Buffer
buffer.WriteString("ready")
If a type cannot operate safely without configuration or dependencies, prevent invalid construction with unexported fields and a constructor.
type Client struct {
baseURL *url.URL
http *http.Client
}
func NewClient(baseURL string, httpClient *http.Client) (*Client, error)
Document whether the caller or package owns injected resources. A package should not close a shared client it did not create unless the contract explicitly transfers ownership.
Keep interfaces at the consumer
type LessonStore interface {
Find(context.Context, LessonID) (Lesson, error)
}
The service that needs Find declares the narrow interface. The repository implementation can expose a concrete type without predicting every consumer's abstraction.
Return an interface only when callers benefit from multiple hidden implementations or the abstraction is itself the stable product. Returning a concrete value usually preserves more capability and compatibility.
This is guidance, not a mechanical rule; design from the actual contract.
Options and configuration
For a small fixed set of required values, ordinary parameters or a config struct are clearest.
Functional options can help when optional behaviours grow and defaults are stable:
type Option func(*Client) error
func WithTimeout(timeout time.Duration) Option {
return func(client *Client) error {
if timeout <= 0 {
return errors.New("timeout must be positive")
}
client.timeout = timeout
return nil
}
}
Options can also hide which settings are required, complicate validation, and make discoverability worse. Do not use them merely as a style preference.
Context contracts
For request-scoped operations, accept context.Context as the first parameter:
func (c *Client) Fetch(ctx context.Context, id string) (Item, error)
- Do not store ordinary request contexts in a struct.
- Do not accept nil contexts; callers should use
context.Background()orcontext.TODO()when no better context exists. - Return promptly when cancellation can be observed, and document operations that cannot be interrupted.
- Do not add a context parameter to functions that do not perform request-scoped waiting or propagation merely for consistency.
Error contracts
Callers should know which errors they can inspect with errors.Is or errors.As.
var ErrNotFound = errors.New("not found")
Wrapping with %w makes the wrapped error part of the observable API. Once callers depend on it, changing the underlying error can break their logic.
Expose only error identity and detail callers need. Keep messages useful to humans and avoid forcing callers to parse them.
Concurrency and ownership documentation
State whether:
- a value may be used concurrently;
- methods mutate receiver state;
- returned slices or maps share internal storage;
- callbacks run synchronously or in new goroutines;
- the caller must close or release a result;
- a function retains provided buffers after returning.
Silence forces callers to guess.
Compatibility
Adding an exported struct field can affect unkeyed literals. Adding a method to an exported interface breaks external implementations. Changing a wrapped sentinel affects errors.Is. Tightening validation can reject previously accepted input.
Use internal packages to reduce accidental public surface. Export the minimum needed and add compatibility tests for important APIs.
Major incompatible changes require an explicit versioning and migration plan.
Common mistakes
- One package per type: navigation grows without meaningful boundaries.
- A constructor named
Newthat returns invalid values without error: invariants remain unclear. - Exporting fields for test convenience: callers become coupled to internal representation.
- Large provider-owned interfaces: consumers must fake methods they never use.
- Functional options for two obvious arguments: simple calls become indirect.
- Documenting behaviour only in implementation comments: callers cannot discover the contract.
Practice
Design a package for an HTTP-backed weather client. It needs base URL, credentials, timeout, retries for selected requests, concurrent safety, cancellation, and typed not-found/rate-limit errors. Define the public surface and ownership rules without implementing HTTP details.
package weather
var ErrLocationNotFound = errors.New("location not found")
type RateLimitError struct {
RetryAfter time.Duration
}
func (e *RateLimitError) Error() string { return "weather API rate limit exceeded" }
type Config struct {
BaseURL string
APIKey string
Timeout time.Duration
MaxRetries int
}
type Client struct {
// unexported immutable configuration and shared HTTP client
}
func NewClient(config Config, httpClient *http.Client) (*Client, error)
func (c *Client) Current(ctx context.Context, location string) (Conditions, error)
Document that Client is safe for concurrent use, does not close the injected http.Client, validates config without including the API key in errors, retries only documented safe failures with bounded context-aware backoff, and returns ErrLocationNotFound or *RateLimitError for stable caller decisions.
Summary
- Build packages around one coherent responsibility and ownership model.
- Make the zero value useful or prevent invalid construction.
- Declare narrow interfaces where behaviour is consumed.
- Treat contexts, errors, resource ownership, and concurrency as public API.
- Minimise exported surface so future evolution remains possible.
Official references: Effective Go and Go Code Review Comments.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.