Files
zogo/examples/httpc/main.go
T
4566704 a8577b7b3b feat(httpc): go-hua/httpurl 迁入并更名 httpc(HTTP 客户端)
- 原包名 httpurl 看不出是客户端, 更名 httpc; GET/POST/PUT/DELETE/代理/
  Digest 认证, 函数签名不变, 附测试、例程与 README
2026-09-20 12:25:36 +08:00

48 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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{...})
}