lambda/examples/generic_pr/main.go

55 lines
1.1 KiB
Go
Raw Normal View History

2022-03-27 02:18:22 +00:00
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"git.tuxpa.in/a/lambda"
"git.tuxpa.in/a/lambda/parallel"
)
type RequestContext[T any] struct {
req http.Request
ans T
err error
}
func (r *RequestContext[T]) String() string {
return fmt.Sprintf("%+v", r.ans)
}
func do[T any](r *RequestContext[T]) *RequestContext[T] {
r.ans = *new(T)
res, err := http.DefaultClient.Do(&r.req)
if err != nil {
r.err = err
return r
}
defer res.Body.Close()
r.err = json.NewDecoder(res.Body).Decode(&r.ans)
return r
}
type someResult struct {
Title string `json:"title"`
Id int `json:"id"`
}
func main() {
var requests = make([]*RequestContext[someResult], 20)
for i := range requests {
r, _ := http.NewRequest("GET", fmt.Sprintf("https://jsonplaceholder.typicode.com/todos/%d", i+1), nil)
requests[i] = &RequestContext[someResult]{
req: *r,
}
}
results := lambda.Filter(parallel.Map(requests, do[someResult], 4), func(r *RequestContext[someResult]) bool {
return r.err == nil
})
for _, v := range results {
log.Printf("%s", v)
}
}