Hello World,

In order to manage async tasks with callback on http , I have to reply to 
my customer for example with 202 Accepted, and keep some works with a new 
goroutine. I habitually use server.Shutdown() and sync.Waitgroup in order 
to gracefully shutdown the application when all requests and jobs are 
correctly over (plz see below for example). Can I consider the usage of 
Waitgroup.Wait() and Waitgroup.Add() not into the same goroutine safe? 
(i.e. no race)



thx in adv 

Jerome


package main

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "sync"
    "syscall"
)

func main() {
    var (
        wg = &sync.WaitGroup{}
        s  = http.Server{
            Addr:    ":8080",
            Handler: myHandler(wg),
        }
    )

    go func() {
        if err := s.ListenAndServe(); err != nil && err != 
http.ErrServerClosed {
            panic(err)
        }
    }()

    sig := make(chan os.Signal, 1)
    signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
    <-sig

    if err := s.Shutdown(context.Background()); err != nil {
        log.Println(err)
    }

    wg.Wait()
}

func myHandler(wg *sync.WaitGroup) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        wg.Add(1)
        go func() {
            defer wg.Done()
            // do some async job w/ response by callback
            // ...
        }()

        w.WriteHeader(http.StatusAccepted)
    }
}


-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to