Skip to content
This repository has been archived by the owner on Mar 22, 2019. It is now read-only.

Add option for 'StartupHook' #35

Merged
merged 3 commits into from
Feb 18, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add ServeWithOptions
This adds support for options to be added to 'Serve' and the app struct.
Options are implemented following the 'functional options' pattern
(https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis and
https://commandcenter.blogspot.co.uk/2014/01/self-referential-functions-and-design.html).

Future options can be added by creating an exported func that returns a closure
modifying the app struct, like the following:

    func HaltAndCatchFire(literallyCatchFire bool) option {
        return func(a *app) {
            a.haltAndCatchFire = literallyCatchFire
        }
    }

then in user code:

    gracehttp.ServeWithOptions(
        []*http.Server{ &myServer },
        gracehttp.HaltAndCatchFire(true),
    )
  • Loading branch information
kanatohodets committed Feb 18, 2017
commit 45e15f8894bbbff4f6ec766baf51c0c99f0d5c5f
25 changes: 20 additions & 5 deletions gracehttp/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ var (
ppid = os.Getppid()
)

type option func(*app)

// An app contains one or more servers and associated configuration.
type app struct {
servers []*http.Server
Expand Down Expand Up @@ -117,11 +119,7 @@ func (a *app) signalHandler(wg *sync.WaitGroup) {
}
}

// Serve will serve the given http.Servers and will monitor for signals
// allowing for graceful termination (SIGTERM) or restart (SIGUSR2).
func Serve(servers ...*http.Server) error {
a := newApp(servers)

func (a *app) run() error {
// Acquire Listeners
if err := a.listen(); err != nil {
return err
Expand Down Expand Up @@ -172,6 +170,23 @@ func Serve(servers ...*http.Server) error {
}
}

// ServeWithOptions does the same as Serve, but takes a set of options to
// configure the app struct.
func ServeWithOptions(servers []*http.Server, options ...option) error {
a := newApp(servers)
for _, opt := range options {
opt(a)
}
return a.run()
}

// Serve will serve the given http.Servers and will monitor for signals
// allowing for graceful termination (SIGTERM) or restart (SIGUSR2).
func Serve(servers ...*http.Server) error {
a := newApp(servers)
return a.run()
}

// Used for pretty printing addresses.
func pprintAddr(listeners []net.Listener) []byte {
var out bytes.Buffer
Expand Down