gohttp

package module
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: May 8, 2023 License: MIT Imports: 18 Imported by: 6

README

GoHTTP

GoDev Go CoverageStatus GoReportCard

Package GoHTTP is an elegant and simple HTTP library for Go.

Installation

go get -u github.com/sunshineplan/gohttp

Documentation

https://pkg.go.dev/github.com/sunshineplan/gohttp

License

The MIT License (MIT)

Usage examples

A few usage examples can be found below. See the documentation for the full list of supported functions.

HTTP request
// HTTP GET request
r, _ := gohttp.Get("https://api.github.com/user", gohttp.H{"Authorization": "token"})
fmt.Print(r.StatusCode) // 200
fmt.Print(r.Header.Get("content-type")) // application/json; charset=utf-8
fmt.Print(r.String()) // {"type":"User"...

// HTTP POST request
r, _ = gohttp.Post("https://httpbin.org/post", nil, url.Values{"hello": []string{"world"}})
var data struct { Form struct{ Hello string } }
r.JSON(&data)
fmt.Println(data.Form.Hello) // world

// Upload File
r, _ := gohttp.Upload("https://httpbin.org/post", nil, nil, gohttp.F("readme", "README.md"))
var resp struct {
    Files   struct{ Readme string }
    Headers struct {
        ContentType string `json:"Content-Type"`
    }
}
r.JSON(&resp)
fmt.Println(strings.Split(resp.Files.Readme, "\r\n")[0])     // # GoHTTP
fmt.Println(strings.Split(resp.Headers.ContentType, ";")[0]) // multipart/form-data
Session
// Session provides cookie persistence and configuration
s := gohttp.NewSession()
s.Header.Set("hello", "world")
s.Get("https://httpbin.org/cookies/set/name/value", nil)
r, _ := s.Get("https://httpbin.org/get", nil)
var data struct { Headers struct{ Hello, Cookie string } }
r.JSON(&data)
fmt.Println(data.Headers.Hello)  // world
fmt.Println(data.Headers.Cookie) // name=value

Documentation

Overview

Example
resp, err := Post("https://httpbin.org/post", nil, url.Values{"hello": []string{"world"}})
if err != nil {
	log.Fatal(err)
}
var data struct {
	Form struct{ Hello string }
}
if err := resp.JSON(&data); err != nil {
	log.Fatal(err)
}
fmt.Println(data.Form.Hello)
// world
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetAgent

func SetAgent(agent string)

SetAgent sets default user agent string.

func SetClient

func SetClient(c *http.Client)

SetClient sets default client.

func SetNoProxy

func SetNoProxy()

SetNoProxy sets default client use no proxy.

func SetProxy

func SetProxy(proxy string) error

SetProxy sets default client transport proxy.

func SetProxyFromEnvironment

func SetProxyFromEnvironment()

SetProxyFromEnvironment sets default client use environment proxy.

func SetTimeout added in v1.0.6

func SetTimeout(d time.Duration)

SetTimeout sets default timeout. Zero means no timeout.

Types

type File

type File struct {
	io.ReadCloser
	Fieldname string
	Filename  string
}

File contains the file part of a multipart message.

func F

func F(fieldname, filename string) *File

F opens the file for creating File.

type H

type H map[string]string

H represents the key-value pairs in an HTTP header.

type Response

type Response struct {

	// StatusCode represents the response status code.
	StatusCode int
	// Header maps header keys to values.
	Header http.Header
	// ContentLength records the length of the associated content.
	ContentLength int64
	// contains filtered or unexported fields
}

Response represents the response from an HTTP request.

func Get

func Get(url string, headers H) (*Response, error)

Get issues a GET to the specified URL with headers.

func GetWithClient

func GetWithClient(ctx context.Context, url string, headers H, client *http.Client) (*Response, error)

GetWithClient issues a GET to the specified URL with context, headers and client.

func GetWithContext added in v1.0.6

func GetWithContext(ctx context.Context, url string, headers H) (*Response, error)

GetWithContext issues a GET to the specified URL with context and headers.

func Head(url string, headers H) (*Response, error)

Head issues a HEAD to the specified URL with headers.

func HeadWithClient

func HeadWithClient(ctx context.Context, url string, headers H, client *http.Client) (*Response, error)

HeadWithClient issues a HEAD to the specified URL with context, headers and client.

func HeadWithContext added in v1.0.6

func HeadWithContext(ctx context.Context, url string, headers H) (*Response, error)

HeadWithContext issues a HEAD to the specified URL with context and headers.

func Post

func Post(url string, headers H, data any) (*Response, error)

Post issues a POST to the specified URL with headers. Post data should be one of nil, io.Reader, url.Values, string map or struct.

func PostWithClient

func PostWithClient(ctx context.Context, url string, headers H, data any, client *http.Client) (*Response, error)

PostWithClient issues a POST to the specified URL with context, headers and client.

func PostWithContext added in v1.0.6

func PostWithContext(ctx context.Context, url string, headers H, data any) (*Response, error)

PostWithContext issues a POST to the specified URL with context and headers. Post data should be one of nil, io.Reader, url.Values, string map or struct.

func Upload

func Upload(url string, headers H, params map[string]string, files ...*File) (*Response, error)

Upload issues a POST to the specified URL with a multipart document.

Example
resp, err := Upload("https://httpbin.org/post", nil, nil, F("readme", "README.md"))
if err != nil {
	log.Fatal(err)
}
var data struct {
	Files   struct{ Readme string }
	Headers struct {
		ContentType string `json:"Content-Type"`
	}
}
if err := resp.JSON(&data); err != nil {
	log.Fatal(err)
}
fmt.Println(strings.Split(data.Headers.ContentType, ";")[0])
// multipart/form-data
Output:

func UploadWithClient

func UploadWithClient(ctx context.Context, url string, headers H, params map[string]string, files []*File, client *http.Client) (*Response, error)

UploadWithClient issues a POST to the specified URL with context, a multipart document and client.

func UploadWithContext added in v1.0.6

func UploadWithContext(ctx context.Context, url string, headers H, params map[string]string, files ...*File) (*Response, error)

UploadWithContext issues a POST to the specified URL with context and a multipart document.

func (*Response) Bytes

func (r *Response) Bytes() []byte

Bytes returns a slice of byte of the response body.

func (*Response) Close

func (r *Response) Close() error

Close closes the response body.

func (*Response) Cookies added in v1.0.7

func (r *Response) Cookies() []*http.Cookie

Cookies parses and returns the cookies set in the Set-Cookie headers.

func (*Response) JSON

func (r *Response) JSON(data any) error

JSON parses the response body as JSON-encoded data and stores the result in the value pointed to by data.

func (*Response) Raw added in v1.0.7

func (r *Response) Raw() *http.Response

Raw returns origin *http.Response.

func (*Response) Read added in v1.0.7

func (r *Response) Read(p []byte) (int, error)

Read reads the response body.

func (*Response) Request added in v1.0.7

func (r *Response) Request() *http.Request

Request is the request that was sent to obtain this Response.

func (*Response) Save

func (r *Response) Save(file string) (int, error)

Save saves the response data to file. It returns the number of bytes written and an error, if any.

func (*Response) String

func (r *Response) String() string

String returns the contents of the response body as a string.

type Session

type Session struct {
	*http.Client
	Header http.Header
}

Session provides cookie persistence and configuration.

Example
s := NewSession()
s.Header.Set("hello", "world")
s.Get("https://httpbin.org/cookies/set/name/value", nil)
resp, err := s.Get("https://httpbin.org/get", nil)
if err != nil {
	log.Fatal(err)
}
var data struct {
	Headers struct{ Hello, Cookie string }
}
if err := resp.JSON(&data); err != nil {
	log.Fatal(err)
}
fmt.Println(data.Headers.Hello, data.Headers.Cookie)
// world name=value
Output:

func NewSession

func NewSession() *Session

NewSession creates and initializes a new Session using initial contents.

func (*Session) Cookies

func (s *Session) Cookies(u *url.URL) []*http.Cookie

Cookies returns the cookies to send in a request for the given URL.

func (*Session) Get

func (s *Session) Get(url string, headers H) (*Response, error)

Get issues a session GET to the specified URL with additional headers.

func (*Session) GetWithContext added in v1.0.6

func (s *Session) GetWithContext(ctx context.Context, url string, headers H) (*Response, error)

GetWithContext issues a session GET to the specified URL with context and additional headers.

func (*Session) Head

func (s *Session) Head(url string, headers H) (*Response, error)

Head issues a session HEAD to the specified URL with additional headers.

func (*Session) HeadWithContext added in v1.0.6

func (s *Session) HeadWithContext(ctx context.Context, url string, headers H) (*Response, error)

HeadWithContext issues a session HEAD to the specified URL with context and additional headers.

func (*Session) KeepAlive added in v1.0.1

func (s *Session) KeepAlive(interval *time.Duration, fn func(*Session) error) (err error)

KeepAlive repeatedly calls fn with a fixed interval delay between each call.

func (*Session) Post

func (s *Session) Post(url string, headers H, data any) (*Response, error)

Post issues a session POST to the specified URL with additional headers.

func (*Session) PostWithContext added in v1.0.6

func (s *Session) PostWithContext(ctx context.Context, url string, headers H, data any) (*Response, error)

PostWithContext issues a session POST to the specified URL with context and additional headers.

func (*Session) SetClient

func (s *Session) SetClient(c *http.Client)

SetClient sets default client.

func (*Session) SetCookie

func (s *Session) SetCookie(u *url.URL, name, value string)

SetCookie handles the receipt of the cookie in a reply for the given URL.

func (*Session) SetCookies

func (s *Session) SetCookies(u *url.URL, cookies []*http.Cookie)

SetCookies handles the receipt of the cookies in a reply for the given URL.

func (*Session) SetNoProxy

func (s *Session) SetNoProxy()

SetNoProxy sets Session client use no proxy.

func (*Session) SetProxy

func (s *Session) SetProxy(proxy string) error

SetProxy sets Session client transport proxy.

func (*Session) SetProxyFromEnvironment

func (s *Session) SetProxyFromEnvironment()

SetProxyFromEnvironment sets Session client use environment proxy.

func (*Session) SetTimeout

func (s *Session) SetTimeout(d time.Duration)

SetTimeout sets Session client timeout. Zero means no timeout.

func (*Session) Upload

func (s *Session) Upload(url string, headers H, params map[string]string, files ...*File) (*Response, error)

Upload issues a session POST to the specified URL with a multipart document and additional headers.

func (*Session) UploadWithContext added in v1.0.6

func (s *Session) UploadWithContext(ctx context.Context, url string, headers H, params map[string]string, files ...*File) (*Response, error)

UploadWithContext issues a session POST to the specified URL with context, a multipart document and additional headers.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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