Skip to content

Commit

Permalink
Move http server to httplib package (#135)
Browse files Browse the repository at this point in the history
  • Loading branch information
unanoc authored Feb 3, 2022
1 parent 24031ef commit 12dabb4
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 58 deletions.
58 changes: 0 additions & 58 deletions gin/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,70 +6,12 @@ import (
"net/http"
"os"
"os/signal"
"sync"
"syscall"

"github.com/gin-gonic/gin"
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
}
}()
}

// Deprecated
// SetupGracefulShutdown blocks execution until interruption command sent
func SetupGracefulShutdown(ctx context.Context, port string, engine *gin.Engine) {
Expand Down
66 changes: 66 additions & 0 deletions httplib/server.go
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
}
}()
}

0 comments on commit 12dabb4

Please sign in to comment.