How to do this in Go?

Hello guys! I started learning Go a few days ago and I’m extremely excited. I would like to ask for help on a concurrent issue that I don’t know how to solve. What would my code look like in this case:

There are four distinct servers named respectively “s1”, “s2”, “s3” and “s4”. I need to implement a function that requests a response to each of these four servers. This function should print the name of the server whose response came first. The server response does not matter, it can be your own name.

Also, I need to do a similar function to this one, however, if the server response takes more than 3 seconds, should print an error message.

Thanks for the attention of everyone, waiting hopefully for help.

Hi. The servers are they “just” other go routines listening on the same channel? Or do you mean a full server listening on a socket?

How about this example?

package main

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

func main() {
	c := make(chan string)
	go func() {
		resp, err := http.Head("https://forum.golangbridge.org")
		if err == nil {
			resp.Body.Close()
			c <- resp.Status
			return
		}
		c <- "Failed to connect"
	}()

	// select status
	select {
		case status := <-c:
		fmt.Println(status)
		case <-time.After(3 * time.Second):
		fmt.Println("time is over")
	}
}

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