58 lines
1.5 KiB
Go
58 lines
1.5 KiB
Go
// Run with go run ./examples/httpClient. All HTTP traffic stays on loopback.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"time"
|
|
|
|
"git.yuntuo.hk/k2safe/go-omni/httpc"
|
|
)
|
|
|
|
type result struct {
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
func run() error {
|
|
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Authorization") != "Bearer example-token" {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(result{Message: "authenticated request succeeded"})
|
|
}))
|
|
defer upstream.Close()
|
|
client, err := httpc.New(httpc.Config{
|
|
Proxy: httpc.ProxyConfig{Mode: httpc.ProxyDirect},
|
|
Timeout: 3 * time.Second, DialTimeout: time.Second, TLSHandshakeTimeout: time.Second,
|
|
ResponseHeaderTimeout: time.Second, IdleConnTimeout: 30 * time.Second,
|
|
MaxConnsPerHost: 16, MaxIdleConnsPerHost: 8, MaxIdleConns: 32,
|
|
MaxResponseBytes: 1 << 20, DisableLogging: true,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer client.Close()
|
|
var output result
|
|
if err = client.JSON(context.Background(), http.MethodGet, upstream.URL, nil, &output,
|
|
httpc.WithHeader("Authorization", "Bearer example-token"),
|
|
httpc.WithHeaders(http.Header{"Accept": []string{"application/json"}}),
|
|
httpc.WithMaxResponseBytes(64<<10),
|
|
); err != nil {
|
|
return err
|
|
}
|
|
fmt.Println(output.Message)
|
|
return nil
|
|
}
|
|
func main() {
|
|
if err := run(); err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
}
|