-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move http server to httplib package (#135)
- Loading branch information
Showing
2 changed files
with
66 additions
and
58 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package httplib | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
"sync" | ||
|
||
log "github.com/sirupsen/logrus" | ||
) | ||
|
||
type Server interface { | ||
Run(ctx context.Context, wg *sync.WaitGroup) | ||
} | ||
|
||
type api struct { | ||
router http.Handler | ||
port string | ||
} | ||
|
||
func NewHTTPServer(router http.Handler, port string) Server { | ||
return &api{ | ||
router: router, | ||
port: port, | ||
} | ||
} | ||
|
||
func (a *api) Run(ctx context.Context, wg *sync.WaitGroup) { | ||
a.serve(ctx, wg) | ||
} | ||
|
||
func (a *api) serve(ctx context.Context, wg *sync.WaitGroup) { | ||
wg.Add(1) | ||
|
||
server := &http.Server{ | ||
Addr: ":" + a.port, | ||
Handler: a.router, | ||
} | ||
|
||
serverStopped := make(chan struct{}) | ||
|
||
go func() { | ||
if err := server.ListenAndServe(); err != nil { | ||
log.Error("Server ListenAndServe: ", err) | ||
serverStopped <- struct{}{} | ||
} | ||
}() | ||
|
||
log.WithFields(log.Fields{"bind": a.port}).Info("Starting the API server") | ||
|
||
go func() { | ||
defer func() { wg.Done() }() | ||
|
||
select { | ||
case <-ctx.Done(): | ||
log.Info("Shutting down the server") | ||
|
||
if err := server.Shutdown(context.Background()); err != nil { | ||
log.Info("Server Shutdown: ", err) | ||
} | ||
|
||
return | ||
case <-serverStopped: | ||
return | ||
} | ||
}() | ||
} |