requestx

package
v0.0.0-...-270bddf Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2024 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FormData

type FormData struct {
	Name     string
	Contents []byte
	Filename string
	Filepath string
	Headers  map[string]any
}

FormData multipart form data

type Options

type Options struct {
	Debug   bool
	BaseURI string
	Timeout float32

	Query        any
	Headers      map[string]any
	Cookies      any
	FormParams   map[string]any
	JSON         any
	XML          any
	Multipart    []FormData
	Proxy        string
	Certificates []tls.Certificate
	// contains filtered or unexported fields
}

type Request

type Request struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(opts ...Options) *Request
Example
package main

import (
	"fmt"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	fmt.Printf("%T", cli)
}
Output:

*requestx.Request

func (*Request) Delete

func (r *Request) Delete(uri string, opts ...Options) (*Response, error)
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Delete("http://127.0.0.1:8091/delete")
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("%T", resp)
}
Output:

*requestx.Response

func (*Request) Get

func (r *Request) Get(uri string, opts ...Options) (*Response, error)
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient(requestx.Options{
		BaseURI: "http://127.0.0.1:8091",
	})

	resp, err := cli.Get("/get")
	if err != nil {
		log.Fatalln(err)
	}

	body, _ := resp.GetBody()
	fmt.Printf("%s", body)
}
Output:

http get
Example (WithProxy)
package main

import (
	"fmt"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Get("https://www.test.com/test.php", requestx.Options{
		Timeout: 5.0,
		Proxy:   "http://127.0.0.1:1080",
	})
	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println(resp.GetStatusCode())
	}

}
Output:

Get "https://www.test.com/test.php": proxyconnect tcp: dial tcp 127.0.0.1:1080: connect: connection refused
Example (WithQuery_arr)
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Get("http://127.0.0.1:8091/get-with-query", requestx.Options{
		Query: map[string]interface{}{
			"key1": "value1",
			"key2": []string{"value21", "value22"},
			"key3": "abc",
		},
	})
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("%s", resp.GetRequest().URL.RawQuery)
}
Output:

key1=value1&key2=value21&key2=value22&key3=abc
Example (WithQuery_str)
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Get("http://127.0.0.1:8091/get-with-query?key0=value0", requestx.Options{
		Query: "key1=value1&key2=value21&key2=value22&key3=333",
	})
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("%s", resp.GetRequest().URL.RawQuery)
}
Output:

key1=value1&key2=value21&key2=value22&key3=333

func (*Request) Options

func (r *Request) Options(uri string, opts ...Options) (*Response, error)
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Options("http://127.0.0.1:8091/options")
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("%T", resp)
}
Output:

*requestx.Response

func (*Request) Patch

func (r *Request) Patch(uri string, opts ...Options) (*Response, error)
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Patch("http://127.0.0.1:8091/patch")
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("%T", resp)
}
Output:

*requestx.Response

func (*Request) Post

func (r *Request) Post(uri string, opts ...Options) (*Response, error)
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Post("http://127.0.0.1:8091/post")
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("%T", resp)
}
Output:

*requestx.Response
Example (WithCookies_map)
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Post("http://127.0.0.1:8091/post-with-cookies", requestx.Options{
		Cookies: map[string]interface{}{
			"cookie1": "value1",
			"cookie2": "value2",
		},
	})
	if err != nil {
		log.Fatalln(err)
	}

	body, _ := resp.GetBody()
	fmt.Printf("%T", body)
}
Output:

requestx.ResponseBody
Example (WithCookies_obj)
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	cookies := make([]*http.Cookie, 0, 2)
	cookies = append(cookies, &http.Cookie{
		Name:     "cookie133",
		Value:    "value1",
		Domain:   "httpbin.org",
		Path:     "/cookies",
		HttpOnly: true,
	})
	cookies = append(cookies, &http.Cookie{
		Name:   "cookie2",
		Value:  "value2",
		Domain: "httpbin.org",
		Path:   "/cookies",
	})

	resp, err := cli.Post("http://127.0.0.1:8091/post-with-cookies", requestx.Options{
		Cookies: cookies,
	})
	if err != nil {
		log.Fatalln(err)
	}

	body, _ := resp.GetBody()
	fmt.Printf("%T", body)
}
Output:

requestx.ResponseBody
Example (WithCookies_str)
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Post("http://127.0.0.1:8091/post-with-cookies", requestx.Options{
		Cookies: "cookie1=value1;cookie2=value2",
	})
	if err != nil {
		log.Fatalln(err)
	}

	body, _ := resp.GetBody()
	fmt.Printf("%T", body)
}
Output:

requestx.ResponseBody
Example (WithFormParams)
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Post("http://127.0.0.1:8091/post-with-form-params", requestx.Options{
		Headers: map[string]interface{}{
			"Content-Type": "application/x-www-form-urlencoded",
		},
		FormParams: map[string]interface{}{
			"key1": "value1",
			"key2": []string{"value21", "value22"},
			"key3": "333",
		},
	})
	if err != nil {
		log.Fatalln(err)
	}

	body, _ := resp.GetBody()
	fmt.Println(body)
}
Output:

form params:{"key1":["value1"],"key2":["value21","value22"],"key3":["333"]}
Example (WithHeaders)
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Post("http://127.0.0.1:8091/post-with-headers", requestx.Options{
		Headers: map[string]interface{}{
			"User-Agent": "testing/1.0",
			"Accept":     "application/json",
			"X-Foo":      []string{"Bar", "Baz"},
		},
	})
	if err != nil {
		log.Fatalln(err)
	}

	headers := resp.GetRequest().Header["X-Foo"]
	fmt.Println(headers)
}
Output:

[Bar Baz]
Example (WithJSON)
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Post("http://127.0.0.1:8091/post-with-json", requestx.Options{
		Headers: map[string]any{
			"Content-Type": "application/json",
		},
		JSON: struct {
			Key1 string   `json:"key1"`
			Key2 []string `json:"key2"`
			Key3 int      `json:"key3"`
		}{"value1", []string{"value21", "value22"}, 333},
	})
	if err != nil {
		log.Fatalln(err)
	}

	body, _ := resp.GetBody()
	fmt.Println(body)
}
Output:

json:{"key1":"value1","key2":["value21","value22"],"key3":333}
Example (WithMultipart)
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient(requestx.Options{
		Debug: false,
	})

	resp, err := cli.Post("http://127.0.0.1:8091/post-with-multipart", requestx.Options{
		Multipart: []requestx.FormData{
			{
				Name:     "foo",
				Contents: []byte("bar"),
			},
			{
				Name:     "json",
				Contents: []byte(`{"title":"title","intro":"introduction"}`),
			},
			{
				Name:     "media",
				Filepath: "./image.png",
			},
		},
	})
	if err != nil {
		log.Fatalln(err)
	}

	body, _ := resp.GetBody()
	fmt.Println(string(body.Read(10)))
}
Output:

body:
Example (WithStreamResponse)
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Post("http://127.0.0.1:8091/post-with-stream-response", requestx.Options{
		Headers: map[string]interface{}{
			"Accept": "text/event-stream",
		},
		JSON: map[string]interface{}{
			"foo": "bar",
		},
	})
	if err != nil {
		log.Fatalln(err)
	}

	if !strings.HasPrefix(resp.GetHeaderLine("content-type"), "text/event-stream") {
		body, _ := resp.GetBody()
		log.Fatalf("get stream failed: %s\n", body)
	}

	var message []byte

	for data := range resp.Stream() {
		log.Printf("stream data: %s\n", data)
		message = append(message, data...)
	}

	if err := resp.Err(); err != nil {
		log.Fatalf("stream closed with error: %v\n", err)
	}

	// log.Printf("%s", message)
	fmt.Printf("%s", message)
}
Output:

this message will response with stream
Example (WithXML)
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Post("http://127.0.0.1:8091/post-with-xml", requestx.Options{
		XML: map[string]interface{}{
			"out_trade_no": "xxx",
			"total_fee":    333,
		},
	})
	if err != nil {
		log.Fatalln(err)
	}

	body, _ := resp.GetBody()
	fmt.Println(string(body.Read(9)))
}
Output:

xml:<xml>

func (*Request) Put

func (r *Request) Put(uri string, opts ...Options) (*Response, error)
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()

	resp, err := cli.Put("http://127.0.0.1:8091/put")
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("%T", resp)
}
Output:

*requestx.Response

func (*Request) Request

func (r *Request) Request(method, uri string, opts ...Options) (*Response, error)

func (*Request) SetOptions

func (r *Request) SetOptions(opts Options)

SetOptions set request options

type Response

type Response struct {
	// contains filtered or unexported fields
}

func Delete

func Delete(uri string, opts ...Options) (*Response, error)

func Get

func Get(uri string, opts ...Options) (*Response, error)
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	resp, err := requestx.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	body, _ := resp.GetBody()
	fmt.Printf("%s", body)
}
Output:

http get

func Patch

func Patch(uri string, opts ...Options) (*Response, error)

func Post

func Post(uri string, opts ...Options) (*Response, error)

func Put

func Put(uri string, opts ...Options) (*Response, error)

func (*Response) Err

func (r *Response) Err() error

func (*Response) GetBody

func (r *Response) GetBody() (ResponseBody, error)

GetBody 获取body体

Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	body, err := resp.GetBody()
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("%T", body)
}
Output:

requestx.ResponseBody

func (*Response) GetHeader

func (r *Response) GetHeader(name string) []string
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	header := resp.GetHeader("content-type")
	fmt.Printf("%T", header)
}
Output:

[]string

func (*Response) GetHeaderLine

func (r *Response) GetHeaderLine(name string) string

GetHeaderLine 获取指定header的第一个值

Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	header := resp.GetHeaderLine("content-type")
	fmt.Printf("%T", header)
}
Output:

string

func (*Response) GetHeaders

func (r *Response) GetHeaders() map[string][]string
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	headers := resp.GetHeaders()
	fmt.Printf("%T", headers)
}
Output:

map[string][]string

func (*Response) GetParsedBody

func (r *Response) GetParsedBody() (*gjson.Result, error)

GetParsedBody 获取json格式的body体 gjson.Result

Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get-response-json")
	if err != nil {
		log.Fatalln(err)
	}

	body, err := resp.GetParsedBody()
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("%T,%v,%v", body, body.Get("code").Int(), body.Get("message").String())
}
Output:

*gjson.Result,10001,参数错误

func (*Response) GetReasonPhrase

func (r *Response) GetReasonPhrase() string

GetReasonPhrase 获取响应状态说明

Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println(resp.GetReasonPhrase())
}
Output:

OK

func (*Response) GetRequest

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

GetRequest 获取请求

func (*Response) GetStatusCode

func (r *Response) GetStatusCode() int
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println(resp.GetStatusCode())
}
Output:

200

func (*Response) HasHeader

func (r *Response) HasHeader(name string) bool
Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	flag := resp.HasHeader("Content-Type")
	fmt.Printf("%T", flag)
}
Output:

bool

func (*Response) IsTimeout

func (r *Response) IsTimeout() bool
Example
package main

import (
	"fmt"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient(requestx.Options{
		Timeout: 0.9,
	})
	resp, err := cli.Get("http://127.0.0.1:8091/get-timeout")
	if err != nil {
		if resp.IsTimeout() {
			fmt.Println("timeout")

			return
		}
	}

	fmt.Println("not timeout")
}
Output:

timeout

func (*Response) Stream

func (r *Response) Stream() chan []byte

type ResponseBody

type ResponseBody []byte

func (ResponseBody) GetContents

func (r ResponseBody) GetContents() string

GetContents 获取body体字符串

Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	body, err := resp.GetBody()
	if err != nil {
		log.Fatalln(err)
	}

	contents := body.GetContents()

	fmt.Printf("%T", contents)
}
Output:

string

func (ResponseBody) Read

func (r ResponseBody) Read(length int) []byte

Read 读取指定长度的body体

Example
package main

import (
	"fmt"
	"log"

	"github.com/yu1ec/go-pkg/requestx"
)

func main() {
	cli := requestx.NewClient()
	resp, err := cli.Get("http://127.0.0.1:8091/get")
	if err != nil {
		log.Fatalln(err)
	}

	body, err := resp.GetBody()
	if err != nil {
		log.Fatalln(err)
	}

	contents := body.Read(30)

	fmt.Printf("%T", contents)
}
Output:

[]uint8

func (ResponseBody) String

func (r ResponseBody) String() string

String 获取body体字符串

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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