Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shut down cleanly when 'api serve' is interrupted #1219

Merged
merged 1 commit into from
Oct 24, 2023
Merged
Changes from all commits
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
29 changes: 21 additions & 8 deletions cmd/api_serve.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package cmd

import (
stdcontext "context"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"syscall"

"github.com/aptly-dev/aptly/api"
"github.com/aptly-dev/aptly/systemd/activation"
Expand Down Expand Up @@ -55,6 +59,17 @@ func aptlyAPIServe(cmd *commander.Command, args []string) error {
listen := context.Flags().Lookup("listen").Value.String()
fmt.Printf("\nStarting web server at: %s (press Ctrl+C to quit)...\n", listen)

server := http.Server{Handler: api.Router(context)}

sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)
go (func() {
if _, ok := <-sigchan; ok {
server.Shutdown(stdcontext.Background())
}
})()
defer close(sigchan)

listenURL, err := url.Parse(listen)
if err == nil && listenURL.Scheme == "unix" {
file := listenURL.Path
Expand All @@ -67,19 +82,17 @@ func aptlyAPIServe(cmd *commander.Command, args []string) error {
}
defer listener.Close()

err = http.Serve(listener, api.Router(context))
if err != nil {
return fmt.Errorf("unable to serve: %s", err)
}
return nil
err = server.Serve(listener)
} else {
server.Addr = listen
err = server.ListenAndServe()
}

err = http.ListenAndServe(listen, api.Router(context))
if err != nil {
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("unable to serve: %s", err)
}

return err
return nil
}

func makeCmdAPIServe() *commander.Command {
Expand Down
Loading