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


(Yash Soni) #1

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.


(Lutz Horn) #2
  • 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.

(Yash Soni) #3

Looks convincing but can you please throw an example ?


(Lutz Horn) #4

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


(Yash Soni) #5

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


(Yash Soni) #6

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


(Lutz Horn) #7

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.


(Yash Soni) #8

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


(Lutz Horn) #9

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


(Yash Soni) #10

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.


(Yash Soni) #11

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