How to run extra routine for http server properly ?

147 views
Skip to first unread message

alex-coder

unread,
Jul 5, 2023, 10:03:47 AM7/5/23
to golang-nuts
Hi All !

So, http server looks like is a request / response processing.
But in case it is nesessary to do something else after the response has been sent to the client, how to do it properly ?
Is there any example to read ?

Thank you.


ben...@gmail.com

unread,
Jul 5, 2023, 7:33:18 PM7/5/23
to golang-nuts
For simple things, you can fire up a goroutine to do the "something else" after the request finishes. For example, I've used this before to kick off sending an email to a customer in the background (you'll want to handle/report errors somehow though):

package main

import (
"fmt"
"log"
"net/http"
"time"
)

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "sending email in the background")
go sendEmail()
// response is sent, but sendEmail goroutine continues
})
log.Print("listening on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}

func sendEmail() {
log.Printf("would send an email here")
time.Sleep(time.Second)
log.Printf("done sending email")
}

alex-coder

unread,
Jul 7, 2023, 3:58:03 AM7/7/23
to golang-nuts
Yes, the question is set too broadly, it is necessary to specify the context, 
thank you.

четверг, 6 июля 2023 г. в 02:33:18 UTC+3, ben...@gmail.com:

Brian Candler

unread,
Jul 7, 2023, 9:59:50 AM7/7/23
to golang-nuts
If it's an important business task which needs to take place even if the machine crashes, then maybe you want to post a request into a persistent message queue (e.g. NATS, Kafka) before returning to the user.

The task can then be picked up by a separate worker process.

Reply all
Reply to author
Forward
0 new messages