crawl

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2022 License: MIT Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

This project solving a problem of requesting N queries on n GoRoutines(threads)

Run test

go test

Init mod

go mod init github.com/DokuroGitHub/go-crawl

Get dependencies

go get .

Using Colorize

go get github.com/TwiN/go-color

Sender

func sendValue(c chan<- string, wg *sync.WaitGroup, nURLs int) {
	defer wg.Done()
	for i := 1; i <= nURLs; i++ {
		item := color.InBlack("[") + color.InBlue(fmt.Sprintf("URL%03d", +i)) + color.InBlack("]")
		c <- item
		fmt.Println(color.Autof(item) + ": enqueued")
	}
	close(c)
	fmt.Println(color.InGreen("Channel has closed"))
}

Receiver

func receiveValue(c <-chan string, wg *sync.WaitGroup, nWorkers, sPerURL int) {
	defer wg.Done()
	for i := 1; i <= nWorkers; i++ {
		wg.Add(1)
		worker := color.InBlack("[") + color.InPurple(fmt.Sprintf("Worker%02d", +i)) + color.InBlack("]")
		go func() {
			defer wg.Done()
			for item := range c {
				fmt.Println(color.Autof(item) + ":" + color.Autof(worker) + color.InCyan(": running"))
				time.Sleep(time.Second * time.Duration(sPerURL))
				fmt.Println(color.Autof(item) + color.InGreen(": finished"))
			}
			fmt.Println(color.Autof(worker) + color.InGreen(": finished"))
		}()
	}
}

Crawl

func Crawl(numberOfURLs, numberOfWorkers, secondsPerURL, channelCap int) error {
	if numberOfURLs < 0 {
		return errors.New("numberOfURLs can not be positive (>=0)")
	}
	if numberOfWorkers <= 0 {
		return errors.New("numberOfWorkers must be positive (>0)")
	}
	if secondsPerURL <= 0 {
		return errors.New("secondsPerURL must be positive (>0)")
	}
	if channelCap <= 0 {
		return errors.New("channelCap must be positive (>0)")
	}

	// WaitGroup
	wg := &sync.WaitGroup{}
	wg.Add(2) // .Done() in sendValue() + receiveValue()

	// channel
	c := make(chan string, channelCap)

	// sender
	go sendValue(c, wg, numberOfURLs)

	// receiver
	go receiveValue(c, wg, numberOfWorkers, secondsPerURL)

	// wait
	wg.Wait()
	fmt.Print(color.InGreen("Crawl ended\n"))

	return nil
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Crawl

func Crawl(numberOfURLs, numberOfWorkers, secondsPerURL, channelCap int) error

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址