How to return json structure to an api immediately after it crosses 5 seconds

I have a golang function function that handles several transactions and the response needs to be sent within 5 seconds. How can I can keep checking during function execution to return a default false if the code takes more than 5 seconds.

  • Open a channel the function writes to if it is finished.
  • Start the function as a Goroutine, pass the channel to it.
  • In the calling function, loop and wait for five seconds for a write on the channel.
  • If the Goroutine writes to the channel, return success.
  • If not, return failure.

Looks convincing but can you please throw an example ?

Here you go:

package main

import (
	"fmt"
	"time"
)

// Sub takes some time to finish, then it signals this on the channel.
func Sub(done chan<- bool) {
	time.Sleep(3 * time.Second)
	done <- true
	close(done)
}

// Tick waits for at most five seconds. To show us something, return `false`
// every second.
func Tick(done chan<- bool) {
	for i := 5; i > 0; i-- {
		time.Sleep(time.Second)
		done <- false
	}
	close(done)
}

func main() {
	done := make(chan bool)

	// Start both functions in Goroutines, pass the channel to both.
	go Sub(done)
	go Tick(done)

	// Listen on the channel. As soon as any of the function closes it, we are
	// done.
	for b := range done {
		fmt.Printf("done: %v\n", b)
	}
}

https://play.golang.com/p/Y9vApBgEO5G

Both functions Sub and Tick ran paralley right, then how does the channel knows exit after true ?

Ok got it you are closing the channel. Thanks buddy!

Both functions call close(done) on the channel. After this, none of them will be able write on it. And the main function, which loops over the channel using range, recognizes that the channel has been closed and exits the loop.

1 Like

True but what do with multiple requests coming at the same time ?

That sounds like a different question. How about formulating a new one?

Yeah what I want to do is I have a function that handles multiple transactional requests. So response to each request should be within 5 seconds.

@lutzhorn I have a function that handles multiple transactional requests. So response to each request should be within 5 seconds

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.