Documentation
¶
Overview ¶
Example (Authentication) ¶
package main
import (
"context"
"fmt"
"log"
"github.com/soyacen/goose/outgoing"
)
func main() {
result, err := outgoing.Get().
URL(outgoing.URLString("https://httpbin.org/headers")).Query().
Header(outgoing.BearerAuth("your-token-here")).Body().
// 或者使用基本认证
// Header(outgoing.BasicAuth("username", "password")).
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
fmt.Printf("Status: %d\n", result.StatusCode())
body, _ := result.TextBody()
fmt.Printf("Response: %s\n", body)
}
Output:
Example (BasicGet) ¶
package main
import (
"context"
"fmt"
"log"
"github.com/soyacen/goose/outgoing"
)
func main() {
// 创建一个基本的GET请求
result, err := outgoing.Get().
URL(outgoing.URLString("https://httpbin.org/get")).
Query(outgoing.SetQuery("key1", "value1"), outgoing.SetQuery("key2", "value2")).
Header(outgoing.SetHeader("X-Custom-Header", "custom-value")).
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
fmt.Printf("Status: %d\n", result.StatusCode())
body, _ := result.TextBody()
fmt.Printf("Response body: %s\n", body)
}
Output:
Example (BytesBody) ¶
package main
import (
"context"
"fmt"
"log"
"github.com/soyacen/goose/outgoing"
)
func main() {
payload := []byte(`{"custom_format":true,"data":"some binary data..."}`)
result, err := outgoing.Post().
URL(outgoing.URLString("https://httpbin.org/post")).Query().
Header(outgoing.SetHeader("Content-Type", "application/custom-type")).
Body(outgoing.BytesBody(payload, "application/custom-type")).
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
fmt.Printf("Status: %d\n", result.StatusCode())
}
Output:
Example (ComplexQuery) ¶
package main
import (
"context"
"fmt"
"log"
"github.com/soyacen/goose/outgoing"
)
func main() {
type Params struct {
Limit int `url:"limit"`
Offset int `url:"offset"`
Sort string `url:"sort"`
Filter string `url:"filter"`
}
params := Params{
Limit: 10,
Offset: 20,
Sort: "created_at",
Filter: "active",
}
result, err := outgoing.Get().
URL(outgoing.URLString("https://httpbin.org/get")).
Query(outgoing.QueryObject(params)).Header().Body().
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
fmt.Printf("Status: %d\n", result.StatusCode())
}
Output:
Example (FormPost) ¶
package main
import (
"context"
"fmt"
"log"
"net/url"
"github.com/soyacen/goose/outgoing"
)
func main() {
formData := url.Values{}
formData.Set("username", "testuser")
formData.Set("password", "password123")
result, err := outgoing.Post().
URL(outgoing.URLString("https://httpbin.org/post")).
Body(outgoing.FormBody(formData)).
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
fmt.Printf("Status: %d\n", result.StatusCode())
}
Output:
Example (HandlingResponseBody) ¶
package main
import (
"bytes"
"context"
"fmt"
"log"
"github.com/soyacen/goose/outgoing"
)
func main() {
result, err := outgoing.Get().
URL(outgoing.URLString("https://httpbin.org/json")).Query().Header().Body().
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
// 获取字节形式的响应体
bytesBody, err := result.BytesBody()
if err != nil {
log.Printf("Error reading bytes: %v", err)
return
}
fmt.Printf("Body size: %d bytes\n", len(bytesBody))
// 获取文本形式的响应体
textBody, err := result.TextBody()
if err != nil {
log.Printf("Error reading text: %v", err)
return
}
fmt.Printf("First 50 chars of response: %.50s...\n", textBody)
// 将响应写入自定义的writer
var buf bytes.Buffer
err = result.Body(&buf)
if err != nil {
log.Printf("Error writing to buffer: %v", err)
return
}
fmt.Printf("Wrote %d bytes to buffer\n", buf.Len())
}
Output:
Example (MultipartUpload) ¶
package main
import (
"context"
"fmt"
"log"
"strings"
"github.com/soyacen/goose/outgoing"
)
func main() {
// 创建一个模拟的文件
fileContent := strings.NewReader("this is a file content")
var formData []*outgoing.FormData
formData = append(formData, &outgoing.FormData{
FieldName: "file",
File: fileContent,
Filename: "test.txt",
})
formData = append(formData, &outgoing.FormData{
FieldName: "description",
Value: "Test file upload",
})
result, err := outgoing.Post().
URL(outgoing.URLString("https://httpbin.org/post")).
Body(outgoing.MultipartBody(formData...)).
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
fmt.Printf("Status: %d\n", result.StatusCode())
}
Output:
Example (MultipleHeadersAndCookies) ¶
package main
import (
"context"
"fmt"
"log"
"net/http"
"github.com/soyacen/goose/outgoing"
)
func main() {
// 创建一个cookie
cookie := &http.Cookie{
Name: "session_id",
Value: "abc123",
}
result, err := outgoing.Put().
URL(outgoing.URLString("https://httpbin.org/put")).Query().
Header(
outgoing.SetHeader("X-Custom-Header", "value1"),
outgoing.AddHeader("X-Custom-Header", "value2"), // 添加另一个同名头部
outgoing.UserAgent("MyApp/1.0"),
outgoing.SetCookie(cookie),
).
Body(outgoing.TextBody(`{"updated": true}`, "application/json")).
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
fmt.Printf("Status: %d\n", result.StatusCode())
}
Output:
Example (PostJSON) ¶
package main
import (
"context"
"fmt"
"log"
"github.com/soyacen/goose/outgoing"
)
func main() {
type Request struct {
Name string `json:"name"`
Email string `json:"email"`
}
type Response struct {
JSON map[string]interface{} `json:"json"`
}
req := Request{Name: "John Doe", Email: "john@example.com"}
result, err := outgoing.Post().
URL(outgoing.URLString("https://httpbin.org/post")).
Query().
Header(outgoing.SetHeader("Content-Type", "application/json")).
Body(outgoing.JSONBody(req)).
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
var resp Response
if err := result.JSONBody(&resp); err != nil {
log.Printf("Error parsing response: %v", err)
return
}
fmt.Printf("Posted name: %s\n", resp.JSON["json"].(map[string]interface{})["name"])
}
Output:
Example (WithClientAndTimeout) ¶
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
"github.com/soyacen/goose/outgoing"
)
func main() {
client := &http.Client{
Timeout: 10 * time.Second,
}
type Request struct {
Message string `json:"message"`
}
req := Request{Message: "Hello World"}
result, err := outgoing.Post(outgoing.Client(client)).
URL(outgoing.URLString("https://httpbin.org/post")).
Body(outgoing.JSONBody(req)).
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
fmt.Printf("Status: %d\n", result.StatusCode())
}
Output:
Example (WithMiddleware) ¶
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
"github.com/soyacen/goose/client"
"github.com/soyacen/goose/outgoing"
)
func main() {
// 定义一个简单的中间件记录请求时间
loggingMiddleware := func(cli *http.Client, req *http.Request, invoker client.Invoker) (*http.Response, error) {
start := time.Now()
fmt.Printf("Making request to: %s %s\n", req.Method, req.URL.String())
resp, err := invoker(cli, req)
fmt.Printf("Request completed in: %v\n", time.Since(start))
return resp, err
}
result, err := outgoing.Get(outgoing.Middleware(loggingMiddleware)).
URL(outgoing.URLString("https://httpbin.org/get")).
Send(context.Background())
if err != nil {
log.Printf("Error: %v", err)
return
}
fmt.Printf("Status: %d\n", result.StatusCode())
}
Output:
Index ¶
- type BodyOption
- func Body(body io.Reader, contentType string) BodyOption
- func BytesBody(body []byte, contentType string) BodyOption
- func FormBody(form url.Values) BodyOption
- func FormObjectBody(body any) BodyOption
- func GobBody(body any) BodyOption
- func JSONBody(body any) BodyOption
- func MultipartBody(formData ...*FormData) BodyOption
- func ObjectBody(body any, marshal func(any) ([]byte, error), contentType string) BodyOption
- func ProtobufBody(body proto.Message) BodyOption
- func TextBody(body string, contentType string) BodyOption
- func XMLBody(body any) BodyOption
- type BodyOptions
- type BodySetter
- type FormData
- type HeaderOption
- func AddCookie(cookie *http.Cookie) HeaderOption
- func AddHeader(key, value string, uncanonical ...bool) HeaderOption
- func BasicAuth(username, password string) HeaderOption
- func BearerAuth(token string) HeaderOption
- func CacheControl(directives ...string) HeaderOption
- func Cookies(cookies ...*http.Cookie) HeaderOption
- func CustomAuth(scheme, token string) HeaderOption
- func DelCookie(cookie *http.Cookie) HeaderOption
- func DelHeader(key string) HeaderOption
- func Headers(header http.Header) HeaderOption
- func IfMatch(etags ...string) HeaderOption
- func IfModifiedSince(t time.Time) HeaderOption
- func IfNoneMatch(etag string) HeaderOption
- func IfUnmodifiedSince(t time.Time) HeaderOption
- func SetCookie(cookie *http.Cookie) HeaderOption
- func SetHeader(key, value string, uncanonical ...bool) HeaderOption
- func UserAgent(ua string) HeaderOption
- type HeaderOptions
- type HeaderSetter
- type MarshalError
- type MethodOption
- type MethodOptions
- type MethodSetter
- type QueryOption
- type QueryOptions
- type QuerySetter
- type Receiver
- type Sender
- type URLOption
- type URLOptions
- type URLSetter
- func Connect(opts ...MethodOption) URLSetter
- func Delete(opts ...MethodOption) URLSetter
- func Get(opts ...MethodOption) URLSetter
- func Head(opts ...MethodOption) URLSetter
- func Method(method string, opts ...MethodOption) URLSetter
- func Options(opts ...MethodOption) URLSetter
- func Patch(opts ...MethodOption) URLSetter
- func Post(opts ...MethodOption) URLSetter
- func Put(opts ...MethodOption) URLSetter
- func Trace(opts ...MethodOption) URLSetter
- type UnmarshalError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BodyOption ¶
type BodyOption func(BodyOptions)
func Body ¶
func Body(body io.Reader, contentType string) BodyOption
Body sets the body of the request.
func BytesBody ¶
func BytesBody(body []byte, contentType string) BodyOption
BytesBody sets the body of the request as bytes.
func FormBody ¶
func FormBody(form url.Values) BodyOption
FormBody sets the body of the request as form data.
func FormObjectBody ¶
func FormObjectBody(body any) BodyOption
FormObjectBody sets the body of the request using an object to generate form data.
func MultipartBody ¶
func MultipartBody(formData ...*FormData) BodyOption
MultipartBody sets the body of the request as multipart form data.
func ObjectBody ¶
ObjectBody sets the body of the request using a custom marshal function.
func ProtobufBody ¶
func ProtobufBody(body proto.Message) BodyOption
ProtobufBody sets the body of the request as Protobuf.
func TextBody ¶
func TextBody(body string, contentType string) BodyOption
TextBody sets the body of the request as text.
type BodyOptions ¶
type BodyOptions interface {
Body(body io.Reader, contentType string)
BytesBody(body []byte, contentType string)
TextBody(body string, contentType string)
ObjectBody(body any, marshal func(any) ([]byte, error), contentType string)
JSONBody(body any)
XMLBody(body any)
ProtobufBody(body proto.Message)
GobBody(body any)
FormBody(form url.Values)
FormObjectBody(body any)
MultipartBody(formData ...*FormData)
}
type BodySetter ¶
type BodySetter interface {
Sender
Body(opts ...BodyOption) Sender
}
type HeaderOption ¶
type HeaderOption func(HeaderOptions)
func AddCookie ¶
func AddCookie(cookie *http.Cookie) HeaderOption
AddCookie adds a cookie to the request.
func AddHeader ¶
func AddHeader(key, value string, uncanonical ...bool) HeaderOption
AddHeader adds a header to the request.
func BasicAuth ¶
func BasicAuth(username, password string) HeaderOption
BasicAuth sets basic authentication credentials to the request.
func BearerAuth ¶
func BearerAuth(token string) HeaderOption
BearerAuth sets bearer authentication token to the request.
func CacheControl ¶
func CacheControl(directives ...string) HeaderOption
CacheControl sets cache control directives to the request.
func Cookies ¶
func Cookies(cookies ...*http.Cookie) HeaderOption
Cookies sets multiple cookies to the request.
func CustomAuth ¶
func CustomAuth(scheme, token string) HeaderOption
CustomAuth sets custom authentication scheme and token to the request.
func DelCookie ¶
func DelCookie(cookie *http.Cookie) HeaderOption
DelCookie deletes a cookie from the request.
func DelHeader ¶
func DelHeader(key string) HeaderOption
DelHeader deletes a header from the request.
func Headers ¶
func Headers(header http.Header) HeaderOption
Headers sets multiple headers to the request.
func IfMatch ¶
func IfMatch(etags ...string) HeaderOption
IfMatch sets the If-Match header to the request.
func IfModifiedSince ¶
func IfModifiedSince(t time.Time) HeaderOption
IfModifiedSince sets the If-Modified-Since header to the request.
func IfNoneMatch ¶
func IfNoneMatch(etag string) HeaderOption
IfNoneMatch sets the If-None-Match header to the request.
func IfUnmodifiedSince ¶
func IfUnmodifiedSince(t time.Time) HeaderOption
IfUnmodifiedSince sets the If-Unmodified-Since header to the request.
func SetCookie ¶
func SetCookie(cookie *http.Cookie) HeaderOption
Cookie sets a cookie to the request.
func SetHeader ¶
func SetHeader(key, value string, uncanonical ...bool) HeaderOption
Header adds a header to the request.
func UserAgent ¶
func UserAgent(ua string) HeaderOption
UserAgent sets the User-Agent header to the request.
type HeaderOptions ¶
type HeaderOptions interface {
SetHeader(key, value string, uncanonical ...bool)
AddHeader(key, value string, uncanonical ...bool)
DelHeader(key string)
Headers(header http.Header)
UserAgent(ua string)
BasicAuth(username, password string)
BearerAuth(token string)
CustomAuth(scheme, token string)
CacheControl(directives ...string)
IfModifiedSince(t time.Time)
IfUnmodifiedSince(t time.Time)
IfNoneMatch(etag string)
IfMatch(etags ...string)
SetCookie(cookie *http.Cookie)
AddCookie(cookie *http.Cookie)
DelCookie(cookie *http.Cookie)
Cookies(cookies ...*http.Cookie)
}
type HeaderSetter ¶
type HeaderSetter interface {
BodySetter
Header(opts ...HeaderOption) BodySetter
}
type MarshalError ¶
func (MarshalError) Error ¶
func (e MarshalError) Error() string
func (MarshalError) Unwrap ¶
func (e MarshalError) Unwrap() error
type MethodOption ¶
type MethodOption func(MethodOptions)
func Client ¶
func Client(client *http.Client) MethodOption
func Middleware ¶
func Middleware(middlewares ...client.Middleware) MethodOption
type MethodOptions ¶
type MethodOptions interface {
Middleware(middlewares ...client.Middleware)
Client(client *http.Client)
}
type MethodSetter ¶
type MethodSetter interface {
Method(method string, opts ...MethodOption) URLSetter
}
type QueryOption ¶
type QueryOption func(QueryOptions)
func AddQuery ¶
func AddQuery(key, value string) QueryOption
func DelQuery ¶
func DelQuery(key string) QueryOption
func Queries ¶
func Queries(queries url.Values) QueryOption
func QueryObject ¶
func QueryObject(obj any) QueryOption
func QueryString ¶
func QueryString(query string) QueryOption
func SetQuery ¶
func SetQuery(key, value string) QueryOption
type QueryOptions ¶
type QuerySetter ¶
type QuerySetter interface {
HeaderSetter
Query(opts ...QueryOption) HeaderSetter
}
type Receiver ¶
type Receiver interface {
Request() *http.Request
Response() *http.Response
Status() string
StatusCode() int
Proto() string
ProtoMajor() int
ProtoMinor() int
ContentLength() int64
TransferEncoding() []string
Headers() http.Header
Trailers() http.Header
Cookies() []*http.Cookie
Body(file io.Writer) error
BytesBody() ([]byte, error)
TextBody() (string, error)
ObjectBody(body any, unmarshal func([]byte, any) error) error
JSONBody(body any) error
XMLBody(body any) error
ProtobufBody(body proto.Message) error
GobBody(body any) error
}
type URLOption ¶
type URLOption func(URLOptions)
type URLOptions ¶
type URLSetter ¶
type URLSetter interface {
URL(opts ...URLOption) QuerySetter
}
func Connect ¶
func Connect(opts ...MethodOption) URLSetter
func Delete ¶
func Delete(opts ...MethodOption) URLSetter
func Get ¶
func Get(opts ...MethodOption) URLSetter
func Head ¶
func Head(opts ...MethodOption) URLSetter
func Method ¶
func Method(method string, opts ...MethodOption) URLSetter
func Options ¶
func Options(opts ...MethodOption) URLSetter
func Patch ¶
func Patch(opts ...MethodOption) URLSetter
func Post ¶
func Post(opts ...MethodOption) URLSetter
func Put ¶
func Put(opts ...MethodOption) URLSetter
func Trace ¶
func Trace(opts ...MethodOption) URLSetter
type UnmarshalError ¶
func (UnmarshalError) Error ¶
func (e UnmarshalError) Error() string
func (UnmarshalError) Unwrap ¶
func (e UnmarshalError) Unwrap() error