-
-
Save vbratkev/1e98c48ff381254f631b573b3341db99 to your computer and use it in GitHub Desktop.
Request worker pool written in Go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package pool | |
import ( | |
"fmt" | |
"net/http" | |
"sync" | |
) | |
var ( | |
MaxPoolQueue = 100 | |
MaxPoolWorker = 10 | |
) | |
type Pool struct { | |
wg *sync.WaitGroup | |
queue chan *http.Request | |
errors chan error | |
} | |
func NewPool() *Pool { | |
return &Pool{ | |
wg: &sync.WaitGroup{}, | |
queue: make(chan *http.Request, MaxPoolQueue), | |
errors: make(chan error), | |
} | |
} | |
func (p *Pool) Add(r *http.Request) { | |
p.wg.Add(1) | |
p.queue <- r | |
} | |
func (p *Pool) Run() error { | |
for i := 0; i < MaxPoolWorker; i++ { | |
go p.doWork() | |
} | |
for { | |
select { | |
case err := <-p.errors: | |
return err | |
default: | |
p.wg.Wait() | |
} | |
} | |
return nil | |
} | |
func (p *Pool) doWork() { | |
for r := range p.queue { | |
fmt.Printf("Request to %s\n", r.Host) | |
p.wg.Done() | |
_, err := http.DefaultClient.Do(r) | |
if err != nil { | |
p.errors <- err | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment