gcurl

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2023 License: MIT Imports: 16 Imported by: 3

README

gcurl

封装http请求,支持get、post、put、delete等请求方式,支持上传文件
封装jsonrpc协议发起post请求

get请求示例1

package main

import (
	"fmt"
	"github.com/jellycheng/gcurl"
)

func main() {
	resp, err := gcurl.Get("http://devapi.nfangbian.com/test.php?a=1&b=hi123")
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%T \r\n", resp) // *gcurl.Response
		respBody,_ := resp.GetBody()
		// 获取接口响应内容
		fmt.Println(respBody.GetContents())
	}
}

get请求示例2

package main

import (
	"fmt"
	"github.com/jellycheng/gcurl"
)

func main() {
	if resp, err := gcurl.Get("http://devapi.nfangbian.com/test.php?a=100&b=b200", gcurl.Options{
		// 追加和覆盖get参数
		Query: map[string]interface{}{
			"user": "123",
			"tags[]": []string{"学习力", "tagN"},
			"nickname": "小小",
			"b":"bxxx",
		},
		Headers: map[string]interface{}{
			"User-Agent": "gcurl/1.0",
			"Accept":     gcurl.ContentTypeJson,
			"X-USERID":   123456,
			"X-Tag":      []string{"go", "php", "java"},
			gcurl.TraceIdHeader: "traceid-abc-123-xyz",
		},
	}); err == nil {
		fmt.Printf("请求参数:%s \r\n", resp.GetRequest().URL.RawQuery)
		respBody,_ := resp.GetBody()
		fmt.Println("响应结果:", respBody.GetContents())

	} else {
		fmt.Println(err)
	}

}

post请求示例

参数优先级FormParams > JSON > XML

package main

import (
	"fmt"
	"github.com/jellycheng/gcurl"
)

func main() {

	resp, err := gcurl.Post("http://devapi.nfangbian.com/test.php?a=2&b=say123", gcurl.Options{
		Headers: map[string]interface{}{
			//"Content-Type": "application/x-www-form-urlencoded",
			"Content-Type": gcurl.ContentTypeForm,
			"User-Agent":    "gcurl/1.0",
			"Authorization": "Bearer access_token1234",
			gcurl.TraceIdHeader: "trace-id-123x",
		},
		Query: map[string]interface{}{
			"user": 123,
			"tags[]": []string{"学习力", "tagN"},
			"nickname": "大大",
			"a": 99,
			"isok":false,
		},
		FormParams: map[string]interface{}{
			"name":      "admin",
			"age":       24,
			"interests[]": []string{"篮球", "旅游", "听音乐"},
			"isAdmin":   true,
		},
	})
	if err != nil {
		fmt.Println(err)
	} else {
		body, _ := resp.GetBody()
		fmt.Println("响应结果:", body)
	}

}


post json示例1

package main

import (
	"fmt"
	"github.com/jellycheng/gcurl"
)

func main() {
	resp, err := gcurl.Post("http://devapi.nfangbian.com/test.php", gcurl.Options{
		Query: map[string]interface{}{
			"user": 123,
			"tags[]": []string{"学习力", "tagN"},
			"nickname": "大大",
			"a": 108,
			"isok":false,
		},
		JSON: map[string]interface{}{
			"name":      "admin",
			"age":       24,
			"interests": []string{"篮球", "旅游", "听音乐"},
			"isAdmin":   true,
		},
	})
	if err != nil {
		fmt.Println(err)
	} else {
		body, _ := resp.GetBody()
		fmt.Println("响应内容", body)
	}

}

post json示例2

package main

import (
	"fmt"
	"github.com/jellycheng/gcurl"
)

func main() {
	resp, err := gcurl.Post("http://devapi.nfangbian.com/test.php?a=2&b=say123", gcurl.Options{
		Headers: map[string]interface{}{
			"User-Agent":    "gcurl/1.0",
			"Authorization": "Bearer access_token1234",
			gcurl.TraceIdHeader: "me-trace-id123",
		},
		Query: map[string]interface{}{
			"user": 123,
			"tags[]": []string{"学习力", "tagN"},
			"nickname": "大大",
			"a": 108,
			"isok":false,
		},
		JSON: map[string]interface{}{
			"name":      "admin",
			"age":       24,
			"interests": []string{"篮球", "旅游", "听音乐"},
			"isAdmin":   true,
		},
	})
	if err != nil {
		fmt.Println(err)
	} else {
		body, _ := resp.GetBody()
		fmt.Println("响应内容", body)
	}

}

post json示例3

package main

import (
	"fmt"
	"github.com/jellycheng/gcurl"
)

func main() {
	// json字符串
	strJson := `{"age":26,"name":"账号admin123"}`
	if resp, err := gcurl.Post("http://devapi.nfangbian.com/test.php?a=2&b=say123", gcurl.Options{
		Headers: map[string]interface{}{
			"User-Agent":    "gcurl/1.0",
			"Authorization": "Bearer access_token1234",
		},
		Query: map[string]interface{}{
			"user": 123,
			"tags[]": []string{"学习力", "tagN"},
			"nickname": "大大",
			"isok":false,
		},
		JSON: strJson,
	}); err != nil {
		fmt.Println(err)
	} else {
		body, _ := resp.GetBody()
		fmt.Println("响应结果:", body)
	}

}

post json示例4

package main

import (
	"fmt"
	"github.com/jellycheng/gcurl"
)

func main() {

	if resp, err := gcurl.Post("http://devapi.nfangbian.com/test.php?a=2&b=say123", gcurl.Options{
		Headers: map[string]interface{}{
			"User-Agent":    "gcurl/1.0",
			"Authorization": "Bearer access_token1234",
		},
		Query: map[string]interface{}{
			"user": 123,
			"tags[]": []string{"学习力", "tagN"},
			"nickname": "大大123",
			"isok":false,
		},
		JSON: struct {
			Key1 string   `json:"key1"`
			Key2 []string `json:"key2"`
			Key3 int      `json:"key3"`
			Key4 bool      `json:"key4"`
		}{"val1,结构体方式作为参数", []string{"val2-1", "val2-2"}, 333,true},
	}); err != nil {
		fmt.Println(err)
	} else {
		body, _ := resp.GetBody()
		fmt.Println("响应结果:", body)
	}

}

jsonrpc请求示例1

package main

import (
	"fmt"
	"github.com/jellycheng/gcurl"
)

func main() {
	jsonrpcReqDto := gcurl.NewJsonRpcReqDto()
	jsonrpcReqDto.Method = `user\info`
	jsonrpcReqDto.Params = "hello"
	if resp, err := gcurl.Post("http://devapi.nfangbian.com/test.php?a=2&b=say123", gcurl.Options{
		Headers: map[string]interface{}{
			"User-Agent":    "gcurl/1.0/jsonrpc2.0",
			gcurl.TraceIdHeader: "traceid-123",
		},
		JSON: jsonrpcReqDto,
	}); err != nil {
		fmt.Println(err)
	} else {
		body, _ := resp.GetBody()
		fmt.Println("响应结果:", body)
	}

}

并发请求示例

使用协程发起并发请求示例
package main

import (
	"context"
	"fmt"
	"github.com/jellycheng/gcurl"
	"sync"
)

func main() {
	wg := gcurl.NewWg()
	result := sync.Map{}
	ctx1, _ := context.WithCancel(context.Background())
	wg.RunApi(ctx1, func(ctx2 context.Context) {
		// 接口1
		resp, err := gcurl.Get("http://devapi.nfangbian.com/test.php?a=1&b=hi123")
		if err != nil {
			result.Store("api_1", err.Error())
		} else {
			respBody, _ := resp.GetBody()
			// 获取接口响应内容
			result.Store("api_1", respBody.GetContents())
		}

	})
	wg.RunApi(ctx1, func(ctx2 context.Context) {
		// 接口2
		resp, err := gcurl.Post("http://devapi.nfangbian.com/test.php?a=2&b=say123", gcurl.Options{
			Headers: map[string]interface{}{
				"Content-Type":      gcurl.ContentTypeForm,
				"User-Agent":        "gcurl/1.0",
				"Authorization":     "Bearer access_token1234",
				gcurl.TraceIdHeader: "trace-id-123x",
			},
			Query: map[string]interface{}{
				"user":     123,
				"tags[]":   []string{"学习力", "tagN"},
				"nickname": "大大",
				"a":        99,
				"isok":     false,
			},
			FormParams: map[string]interface{}{
				"name":        "admin",
				"age":         24,
				"interests[]": []string{"篮球", "旅游", "听音乐"},
				"isAdmin":     true,
			},
		})
		if err != nil {
			result.Store("api_2", err.Error())
		} else {
			respBody, _ := resp.GetBody()
			result.Store("api_2", respBody.GetContents())
		}
	})
	
	wg.Wait()
	// 统一处理api结果
	result.Range(func(key, value interface{}) bool {
		fmt.Println(key, value)
		return true
	})

}

Documentation

Index

Constants

View Source
const (
	ContentTypeJson      = "application/json"
	ContentTypeForm      = "application/x-www-form-urlencoded"
	ContentTypeOctet     = "application/octet-stream"
	ContentTypeMultipart = "multipart/form-data"
	ContentTypeXml       = "application/xml"
	ContentTypeTexthtml  = "text/html"
	ContentTypeTextxml   = "text/xml"
)
View Source
const (
	// DefaultTimeout 默认超时值
	DefaultTimeout = 15 * time.Second
)
View Source
const (
	TraceIdHeader = "X-Trace-Id"
)

Variables

This section is empty.

Functions

func Map2XML

func Map2XML(m map[string]string, rootName ...string) ([]byte, error)

Types

type DefaultLogger

type DefaultLogger struct{}

func NewDefaultLogger

func NewDefaultLogger() *DefaultLogger

func (DefaultLogger) Printf

func (l DefaultLogger) Printf(format string, values ...interface{})

type JsonRpcReqDto

type JsonRpcReqDto struct {
	Jsonrpc string      `json:"jsonrpc"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params,omitempty"`
	Id      interface{} `json:"id"` //字符串、int、unit、int8/16/32/64、uint8/16/32/64、null
}

func NewJsonRpcReqDto

func NewJsonRpcReqDto() JsonRpcReqDto

type JsonRpcRespDto

type JsonRpcRespDto struct {
	Jsonrpc string           `json:"jsonrpc"`
	Result  *json.RawMessage `json:"result,omitempty"`
	Error   *json.RawMessage `json:"error,omitempty"`
	Id      interface{}      `json:"id"`
}

type MyXmldata

type MyXmldata struct {
	XMLName xml.Name
	Data    map[string]string
}

func (MyXmldata) MarshalXML

func (m MyXmldata) MarshalXML(e *xml.Encoder, start xml.StartElement) error

type Options

type Options struct {
	Debug      bool
	Log        WriterLogger
	Timeout    time.Duration
	Query      interface{}
	Headers    map[string]interface{}
	Cookies    interface{}
	FormParams map[string]interface{}
	JSON       interface{}
	XML        interface{}
	Proxy      string
}

func NewOptions

func NewOptions() Options

type RPCError

type RPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

错误对象

type Request

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

func NewClient

func NewClient() *Request

func (*Request) Delete

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

func (*Request) Get

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

func (*Request) GetOptions

func (r *Request) GetOptions() Options

func (*Request) Logf

func (r *Request) Logf(format string, param ...interface{})

func (*Request) Options

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

func (*Request) Patch

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

func (*Request) Post

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

func (*Request) Put

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

func (*Request) Request

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

func (*Request) SetOptions

func (r *Request) SetOptions(o 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)

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) GetBody

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

func (*Response) GetHeader

func (me *Response) GetHeader(name string) string

GetHeader 不区分大小写获取请求头内容

func (*Response) GetHeaderSlice

func (me *Response) GetHeaderSlice(name string) []string

func (*Response) GetHeaders

func (me *Response) GetHeaders() map[string][]string

GetHeaders 获取所有请求头,也可通过 对象.GetRequest().Header获取原生http.Header类型

func (*Response) GetRequest

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

func (*Response) GetStatusCode

func (me *Response) GetStatusCode() int

func (*Response) HasHeader

func (me *Response) HasHeader(name string) bool

HasHeader 不区分大小写判断请求头是否存在

func (*Response) IsTimeout

func (me *Response) IsTimeout() bool

type ResponseBody

type ResponseBody []byte

func (ResponseBody) GetContents

func (me ResponseBody) GetContents() string

func (ResponseBody) String

func (me ResponseBody) String() string

func (ResponseBody) ToByte

func (me ResponseBody) ToByte() []byte

func (ResponseBody) ToString

func (me ResponseBody) ToString() string

type Wg

type Wg struct {
	sync.WaitGroup
}

func NewWg

func NewWg() *Wg

func (*Wg) RunApi

func (w *Wg) RunApi(ctx1 context.Context, callback func(ctx2 context.Context))

type WriterLogger

type WriterLogger interface {
	Printf(string, ...interface{})
}

WriterLogger 日志接口

Jump to

Keyboard shortcuts

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