Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

goroutines-distribuida

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type Response struct {
	Url string `json:"url"`
}

func Load(url string, c chan<- string) {

	// Load the URL
	resp, err := http.Get(url)

	// Check errors
	if err != nil {
		fmt.Println(fmt.Errorf("Error while getting data", err))
		return
	}

	// Connection will be closed when we exit the scope
	defer resp.Body.Close()

	// Parse JSON
	var d Response
	err = json.NewDecoder(resp.Body).Decode(&d)

	// Check errors
	if err != nil {
		fmt.Println(fmt.Errorf("Error while parsing JSON", err))
		return
	}

	// Extract response URL
	responseUrl := d.Url

	// Emit responseUrl
	c <- responseUrl
}

func main() {
	urls := []string{
		"https://httpbin.org/delay/6",
		"https://httpbin.org/delay/3",
		"https://httpbin.org/delay/1",
	}

	channel := make(chan string)

	for _, url := range urls {
	    fmt.Println(fmt.Sprintf("Launching %s", url))
		go Load(url, channel)
	}

	i := 0
	for resp := range channel {
		fmt.Println(resp)
		i++
		if i == 3 {
			break
		}
	}
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.