Skip to content

Instantly share code, notes, and snippets.

@rogerwelin
Created January 28, 2020 22:27
Show Gist options
  • Save rogerwelin/176f882bfbdf0aa6284a9cfbfad12c40 to your computer and use it in GitHub Desktop.
Save rogerwelin/176f882bfbdf0aa6284a9cfbfad12c40 to your computer and use it in GitHub Desktop.
functional operators
package main
import (
"time"
)
type Server struct {
addr string
// default no timeout
timeout time.Duration
}
// Timeout configures a maximum length of idle connection in Server
func Timeout(timeout time.Duration) func(*Server) {
return func(s *Server) {
s.timeout = timeout
}
}
// NewServer initializes a new Server listening on addr with optional configuration
func NewServer(addr string, opts ...func(*Server)) *Server {
server := &Server{
addr: addr,
}
// apply the list of options to Server
for _, opt := range opts {
opt(server)
}
return server
}
func main() {
// configure a timeout in addition to the address
server := NewServer(":8080", Timeout(10*time.Second))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment