Created
January 28, 2020 22:27
-
-
Save rogerwelin/176f882bfbdf0aa6284a9cfbfad12c40 to your computer and use it in GitHub Desktop.
functional operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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