gofetch

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2023 License: MIT Imports: 4 Imported by: 0

README

go-fetch

JS-like Fetch API for Go net/http

Installation

go get github.com/dundunlabs/go-fetch

Usage

package example

import (
    "fmt"
    "net/http"
    "github.com/dundunlabs/go-fetch"
)

func GetExample() {
    res, err := gofetch.Fetch("https://example.com")
    if err != nil {
        fmt.Println("failed to get data: ", err)
	}

	text, err := res.Text()
	if err != nil {
		fmt.Println("failed to read body as text: ", err)
	}

    fmt.Println(text)
}

func PostExample() {
    res, err := gofetch.Fetch("https://example.com", gofetch.Options{
        Method: http.MethodPost,
        Header: http.Header{
            "Content-Type": []string{"application/json"},
        },
        Body: gofetch.BodyJSON(gofetch.H{
            "foo":   "Bar",
        }),
    })
	if err != nil {
        fmt.Println("failed to post data: ", err)
	}

	json, err := res.JSON()
	if err != nil {
		fmt.Println("failed to read body as json: ", err)
	}

    fmt.Println(json)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultOptions = Options{
	Method: http.MethodGet,
}

Functions

func BodyJSON

func BodyJSON(v any) *bytes.Buffer

func BodyText

func BodyText(v string) *bytes.Buffer

Types

type H

type H map[string]any

type Options

type Options struct {
	Method string
	Header http.Header
	Body   io.Reader
}

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

func Fetch

func Fetch(url string, opts ...Options) (*Response, error)

func (*Response) BindJSON

func (res *Response) BindJSON(v any) error

func (*Response) BodyAsBytes

func (res *Response) BodyAsBytes() ([]byte, error)

func (*Response) JSON

func (res *Response) JSON() (map[string]any, error)

func (*Response) Text

func (res *Response) Text() (string, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL