lambda/task/http_request.go

64 lines
1.1 KiB
Go
Raw Normal View History

2022-03-27 02:42:22 +00:00
package task
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type DecoderFunc func(r io.Reader) Decoder
type Decoder interface {
Decode(any) error
}
type HttpRequest[T any] struct {
Req http.Request
ans T
err error
}
2022-03-27 02:43:59 +00:00
func (r *HttpRequest[T]) Ans() T {
return r.ans
}
func (r *HttpRequest[T]) Err() error {
return r.err
}
2022-03-27 02:42:22 +00:00
func (r *HttpRequest[T]) String() string {
return fmt.Sprintf("%+v", r.ans)
}
func (_ *HttpRequest[T]) With(df DecoderFunc) func(r *HttpRequest[T]) *HttpRequest[T] {
return func(r *HttpRequest[T]) *HttpRequest[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 = df(res.Body).Decode(&r.ans)
return r
}
}
func (z *HttpRequest[T]) Json() func(r *HttpRequest[T]) *HttpRequest[T] {
return z.With(func(r io.Reader) Decoder {
return json.NewDecoder(r)
})
}
func (_ *HttpRequest[T]) NoErr() func(r *HttpRequest[T]) bool {
return func(r *HttpRequest[T]) bool {
return r.err == nil
}
}
type someResult struct {
Title string `json:"title"`
Id int `json:"id"`
}