lambda/task/http_request.go

66 lines
1.2 KiB
Go
Raw Normal View History

2022-03-27 02:42:22 +00:00
package task
import (
"encoding/json"
2022-03-27 02:45:23 +00:00
"encoding/xml"
2022-03-27 02:42:22 +00:00
"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)
})
}
2022-03-27 02:45:23 +00:00
func (z *HttpRequest[T]) Xml() func(r *HttpRequest[T]) *HttpRequest[T] {
return z.With(func(r io.Reader) Decoder {
return xml.NewDecoder(r)
})
}
2022-03-27 02:42:22 +00:00
func (_ *HttpRequest[T]) NoErr() func(r *HttpRequest[T]) bool {
return func(r *HttpRequest[T]) bool {
return r.err == nil
}
}