Skip to content

Instantly share code, notes, and snippets.

@rag594
Last active August 18, 2023 08:12
Show Gist options
  • Save rag594/1297879f7d824f4b49aca9af32f4afd1 to your computer and use it in GitHub Desktop.
Save rag594/1297879f7d824f4b49aca9af32f4afd1 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
var wGGlobal sync.WaitGroup
var pollQChannel = make(chan int, 3)
var pollYChannel = make(chan int, 3)
func A() {
fmt.Println("A")
}
func D() {
fmt.Println("C")
}
func B() {
defer func() {
fmt.Println(<-pollQChannel)
}()
fmt.Println("B")
A()
}
func C() {
fmt.Println("C")
defer func() {
fmt.Println(<-pollYChannel)
}()
D()
}
func PollQ(ctx context.Context, gouroutinesWG *sync.WaitGroup) {
defer gouroutinesWG.Done()
for {
select {
case pollQChannel <- 1:
time.Sleep(10 * time.Second)
fmt.Println("Send for processing")
go B()
case <-ctx.Done():
return // exit this function so we don't consume anything more
}
}
}
func PollY(ctx context.Context, gouroutinesWG *sync.WaitGroup) {
defer gouroutinesWG.Done()
for {
select {
case pollYChannel <- 1:
time.Sleep(10 * time.Second)
fmt.Println("Send for processing")
go C()
case <-ctx.Done():
return // exit this function so we don't consume anything more
}
}
}
func main() {
//var wG sync.WaitGroup
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Routes
e.GET("/", hello)
ctx, cancelFunc := context.WithCancel(context.Background())
wGGlobal.Add(2)
go PollQ(ctx, &wGGlobal)
go PollY(ctx, &wGGlobal)
go e.Start(":1323")
gracefullShutdown(e, &wGGlobal, cancelFunc)
}
func hello(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
}
func gracefullShutdown(e *echo.Echo, gouroutinesWG *sync.WaitGroup, cancelFunc context.CancelFunc) {
channel := make(chan os.Signal, 1)
signal.Notify(channel, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
<-channel
log.Println("Service SHUTDOWN")
shutdownCtx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(120))
defer cancel()
log.Println("Waiting for go routines to shut down")
cancelFunc()
gouroutinesWG.Wait()
log.Println("Go routines cleared succesfully to shut down")
e.Shutdown(shutdownCtx)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment