github.com/ars0915/glossika-exercise@v0.0.0-20240904180321-a5617a00d892/router/server.go (about)

     1  package router
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/gin-contrib/pprof"
    10  	"github.com/gin-gonic/gin"
    11  	"github.com/gin-gonic/gin/binding"
    12  	"github.com/go-playground/validator/v10"
    13  	"github.com/pkg/errors"
    14  	"github.com/sirupsen/logrus"
    15  
    16  	"github.com/ars0915/glossika-exercise/config"
    17  	"github.com/ars0915/glossika-exercise/constant"
    18  	"github.com/ars0915/glossika-exercise/util/cGin"
    19  )
    20  
    21  func (rH Handler) RunServer(ctx context.Context) (err error) {
    22  	var (
    23  		httpSrv = &http.Server{
    24  			Addr:    ":" + config.Conf.Core.Port,
    25  			Handler: rH.http.routerEngine(),
    26  		}
    27  		errCh = make(chan error)
    28  	)
    29  
    30  	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
    31  		if err := v.RegisterValidation("password", cGin.ValidatePassword); err != nil {
    32  			errCh <- errors.Wrap(err, "register validation")
    33  		}
    34  	}
    35  
    36  	// http server
    37  	go func() {
    38  		cGin.SetResponseCodePrefix(constant.ResponseCodePrefix)
    39  
    40  		logrus.Info("HTTP server is running on " + config.Conf.Core.Port + " port.")
    41  		if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
    42  			errCh <- errors.Wrap(err, "listen and serve http")
    43  		}
    44  	}()
    45  
    46  	shutdown := func(httpSrv *http.Server) {
    47  		logrus.Warning("Gracefully Shutdown Server ...")
    48  
    49  		var (
    50  			finish      []interface{}
    51  			finishCount int
    52  			finishCh    = make(chan interface{})
    53  		)
    54  
    55  		timeout, timeoutCancel := context.WithTimeout(context.Background(), 5*time.Minute)
    56  		defer timeoutCancel()
    57  
    58  		// Shutdown httpSrv
    59  		finishCount++
    60  		go func() {
    61  			var err error
    62  			defer func() {
    63  				if err != nil {
    64  					finishCh <- err
    65  				} else {
    66  					finishCh <- struct{}{}
    67  				}
    68  			}()
    69  			if err = httpSrv.Shutdown(timeout); err != nil {
    70  				err = errors.Wrap(err, "Shutdown httpSrv")
    71  			}
    72  		}()
    73  
    74  		for {
    75  			select {
    76  			case f := <-finishCh:
    77  				if err, ok := f.(error); ok {
    78  					logrus.Error(err)
    79  				}
    80  				if finish = append(finish, f); len(finish) == finishCount {
    81  					return
    82  				}
    83  			case <-timeout.Done():
    84  				logrus.Error("Gracefully Shutdown Timeout.")
    85  				return
    86  			}
    87  		}
    88  	}
    89  
    90  	select {
    91  	case err := <-errCh:
    92  		return err
    93  	case <-ctx.Done():
    94  		shutdown(httpSrv)
    95  		return nil
    96  	}
    97  }
    98  
    99  func (h HttpHandler) routerEngine() *gin.Engine {
   100  	// set server mode
   101  	gin.SetMode(config.Conf.Core.Mode)
   102  
   103  	r := gin.New()
   104  	r.RedirectTrailingSlash = false
   105  
   106  	if strings.EqualFold(config.Conf.Core.Mode, "DEBUG") {
   107  		pprof.Register(r)
   108  	}
   109  
   110  	r.Use(gin.Recovery())
   111  
   112  	r.GET("_health/", func(ctx *gin.Context) {
   113  		ctx.AbortWithStatus(http.StatusOK)
   114  	})
   115  
   116  	r.GET("/", func(ctx *gin.Context) {
   117  		ctx.JSON(http.StatusOK, gin.H{
   118  			"text": "Welcome to API server.",
   119  		})
   120  	})
   121  
   122  	routers := h.getRouter()
   123  	for _, route := range routers {
   124  		handlerFuncs := []gin.HandlerFunc{}
   125  		if route.requireAuth {
   126  			handlerFuncs = append(handlerFuncs, jwtCheck(h).GinFunc())
   127  		}
   128  		handlerFuncs = append(handlerFuncs, route.worker)
   129  
   130  		r.Handle(route.method, route.endpoint, handlerFuncs...)
   131  	}
   132  
   133  	return r
   134  }