41 lines
904 B
Go
41 lines
904 B
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
func StartServer(ctx context.Context, config struct{ Host, Port string }) error {
|
|
srv := NewServer()
|
|
httpServer := &http.Server{
|
|
Addr: net.JoinHostPort(config.Host, config.Port),
|
|
Handler: srv,
|
|
}
|
|
go func() {
|
|
log.Printf("orphan listening on %s\n", httpServer.Addr)
|
|
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
fmt.Fprintf(os.Stderr, "error listening and serving: %s\n", err)
|
|
}
|
|
}()
|
|
var wg sync.WaitGroup
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
<-ctx.Done()
|
|
shutdownCtx := context.Background()
|
|
shutdownCtx, cancel := context.WithTimeout(shutdownCtx, 10*time.Second)
|
|
defer cancel()
|
|
if err := httpServer.Shutdown(shutdownCtx); err != nil {
|
|
fmt.Fprintf(os.Stderr, "error shutting down http server: %s\n", err)
|
|
}
|
|
}()
|
|
wg.Wait()
|
|
return nil
|
|
}
|