For an incoming HTTP request, I had to respond with a 202 Accepted status code, while continue processing the payload in the background. for example purposes this is what I am currently doing:
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/nbari/violetear"
)
func sleep() {
time.Sleep(3 * time.Second)
fmt.Println("done...")
}
func index(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
go sleep()
}
func main() {
router := violetear.New()
router.HandleFunc("*", index)
http.Handle("/", router)
log.Fatal(http.ListenAndServe(":8080", router))
}
Basically, on the handler I just use WriteHeader
and later a call the the sleep
function within a goroutine:
func index(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
go sleep()
}
In case I would like to respond with "200 OK", I notice that I can simple return, for example:
func index(w http.ResponseWriter, r *http.Request) {
go sleep()
return
}
Therefore wondering if I should return always I want to close:
func index(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
go sleep()
return
}
Or by just writing the header and next calling the goroutine is enough.