package task import ( "encoding/json" "encoding/xml" "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 } func (r *HttpRequest[T]) Ans() T { return r.ans } func (r *HttpRequest[T]) Err() error { return r.err } 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 (z *HttpRequest[T]) Xml() func(r *HttpRequest[T]) *HttpRequest[T] { return z.With(func(r io.Reader) Decoder { return xml.NewDecoder(r) }) } func (_ *HttpRequest[T]) NoErr() func(r *HttpRequest[T]) bool { return func(r *HttpRequest[T]) bool { return r.err == nil } }