56 lines
1005 B
Go
56 lines
1005 B
Go
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
|
|
}
|
|
|
|
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"`
|
|
}
|