Skip to content

Commit

Permalink
Making service to be opened on dynamic port by making serice an insta…
Browse files Browse the repository at this point in the history
…nce var
  • Loading branch information
rajagopal28 committed Aug 1, 2021
1 parent c65259d commit 546d907
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
3 changes: 2 additions & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ import (
)

func main() {
service.Start()
service := service.Service{}
service.Start("")
}
49 changes: 46 additions & 3 deletions service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ package service
import (
"net/http"
"time"
"log"
"os"
"os/signal"
"context"

"pricingengine/service/app"
"pricingengine/service/rpc"
Expand All @@ -12,7 +16,11 @@ import (
)

// Start begins a chi-Mux'd net/http server on port 3000
func Start() {
type Service struct {
Server *http.Server
}

func (s * Service)Start(port string) {
r := chi.NewRouter()

r.Use(middleware.Logger)
Expand All @@ -21,8 +29,43 @@ func Start() {
rpc := rpc.RPC{
App: &app.App{},
}

if len(port) == 0 {
// default port 3000
port = "3000"
}
r.Post("/generate_pricing", rpc.GeneratePricing)
r.Get("/generate_pricing", rpc.GeneratePricingConfig)
http.ListenAndServe(":3000", r)
s.ListenAndServe(":"+port, r)
}

func (s *Service)ListenAndServe(port string, r http.Handler) {
log.Println("Starting Server!")
s.Server = &http.Server{Addr: port, Handler: r}
if err := s.Server.ListenAndServe(); err != nil {
// handle err
}

// Setting up signal capturing
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)

// Waiting for SIGINT (pkill -2)
<-stop
log.Println("Received Server Stop!")
s.Stop()
// Wait for ListenAndServe goroutine to close.
}

// check and stop the currently running http server
func (s * Service)Stop() {
log.Println("Stopping Server!")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if s.Server != nil {
log.Println(" Initiating Server Shutdown!")
if err := s.Server.Shutdown(ctx); err != nil {
// handle err
log.Println("Error while stopping Server!", err)
}
}
}

0 comments on commit 546d907

Please sign in to comment.