- 原包名 httpurl 看不出是客户端, 更名 httpc; GET/POST/PUT/DELETE/代理/ Digest 认证, 函数签名不变, 附测试、例程与 README
48 lines
1.4 KiB
Go
48 lines
1.4 KiB
Go
// httpc 包示例:HTTP 客户端封装(Get/Post/Put/Delete/GetProxy/DigestAuthRequest)
|
||
package main
|
||
|
||
import (
|
||
"fmt"
|
||
"io"
|
||
"net"
|
||
"net/http"
|
||
|
||
"git.zeroonesoft.cn/golib/zogo/httpc"
|
||
)
|
||
|
||
func main() {
|
||
// 启动一个本地测试服务
|
||
mux := http.NewServeMux()
|
||
mux.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
|
||
fmt.Fprintf(w, `{"method":"%s","query":"%s"}`, r.Method, r.URL.RawQuery)
|
||
})
|
||
mux.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) {
|
||
body, _ := io.ReadAll(r.Body)
|
||
fmt.Fprintf(w, `{"method":"%s","body":%s}`, r.Method, string(body))
|
||
})
|
||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||
if err != nil {
|
||
panic(err)
|
||
}
|
||
go http.Serve(l, mux)
|
||
base := "http://" + l.Addr().String()
|
||
|
||
// GET
|
||
body, err := httpc.Get(base+"/get?name=go-hua", nil)
|
||
fmt.Println("GET:", string(body), "err:", err)
|
||
|
||
// POST(默认 Content-Type: application/json)
|
||
body, err = httpc.Post(base+"/post", []byte(`{"id":1}`), nil)
|
||
fmt.Println("POST:", string(body), "err:", err)
|
||
|
||
// 带自定义请求头
|
||
body, err = httpc.Get(base+"/get", map[string]string{"X-Token": "abc123"})
|
||
fmt.Println("GET(带Header):", string(body), "err:", err)
|
||
|
||
// 其他方法用法相同:
|
||
// httpc.Put(url, param, header)
|
||
// httpc.Delete(url, param, header)
|
||
// httpc.GetProxy(url, header, "http://127.0.0.1:7890")
|
||
// httpc.DigestAuthRequest(&httpc.RequestArg{...})
|
||
}
|