0PricingLogin
Go Academy · Lesson

Building a Flexible API

Apply the pattern.

Apply the Pattern

Now assemble the full pattern: a constructor that takes required arguments plus a variadic list of options.

The Variadic Constructor

Required parameters come first; options follow as ...Option.

package main

import "fmt"

type Server struct {
	Host string
	Port int
}
type Option func(*Server)

func WithPort(p int) Option { return func(s *Server) { s.Port = p } }

func NewServer(host string, opts ...Option) *Server {
	s := &Server{Host: host}
	for _, opt := range opts {
		opt(s)
	}
	return s
}

func main() {
	s := NewServer("localhost", WithPort(8080))
	fmt.Printf("%+v\n", *s)
}

All lessons in this course

  1. The Problem with Many Params
  2. Option Functions
  3. Building a Flexible API
  4. Defaults and Validation
← Back to Go Academy