Skip to content

Commit

Permalink
example: stage examples
Browse files Browse the repository at this point in the history
  • Loading branch information
ahuigo committed Oct 9, 2023
1 parent d3fd841 commit d647eda
Show file tree
Hide file tree
Showing 30 changed files with 1,725 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
.vscode/
*.a
*.so

Expand All @@ -26,5 +27,8 @@ _testmain.go
coverage.out
coverage.txt

# Mac osx
.DS_Store

# Exclude intellij IDE folders
.idea/*
1 change: 1 addition & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -1375,6 +1375,7 @@ func createClient(hc *http.Client) *Client {
parseRequestBody,
createHTTPRequest,
addCredentials,
createCurlCmd,
}

// user defined request middlewares
Expand Down
51 changes: 51 additions & 0 deletions example1/req_build_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package examples

import (
ioutil "io"
"regexp"
"testing"

"github.com/ahuigo/requests/v2"
)

// TestBuildRequest
func TestBuildRequest(t *testing.T) {
req, err := requests.BuildRequest("post", "http://baidu.com/a/b/c", requests.Json{
"age": 1,
})
if err != nil {
t.Fatal(err)
}
body, _ := ioutil.ReadAll(req.Body)
expectedBody := `{"age":1}`
if string(body) != expectedBody {
t.Fatal("Failed to build request")
}
}
func TestBuildCurlRequest(t *testing.T) {
req, _ := requests.BuildRequest("post", "https://baidu.com/path?q=curl&v=1", requests.Json{
"age": 1,
})
curl := requests.BuildCurlRequest(req)
if !regexp.MustCompile(`^curl -X POST .+ 'https://baidu.com/path\?q=curl&v=1'`).MatchString(curl) {
t.Fatal(`bad curl cmd: ` + curl)
}
t.Log(curl)
}

func TestBuildRequestHost(t *testing.T) {
req, err := requests.BuildRequest("post", "http://baidu.com/a/b/c", requests.Json{
"age": 1,
})
if err != nil {
t.Fatal(err)
}
if req.Host != "baidu.com" {
t.Fatalf("bad host:%s\n", req.Host)
}

req, _ = requests.BuildRequest("post", "http://baidu.com/a/b/c", requests.Header{"Host": "ahuigo.com"})
if req.Host != "ahuigo.com" {
t.Fatalf("bad host:%s\n", req.Host)
}
}
22 changes: 22 additions & 0 deletions example1/req_header_global_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package examples

import (
"testing"

"github.com/ahuigo/requests/v2"
)

// Set session headers
func TestSendGlobalHeader2(t *testing.T) {
session := requests.R()

headerK := "User-Agent"
headerV := "Custom-Test-Go-User-Agent"
req, err := session.SetGlobalHeader(headerK, headerV).BuildRequest("post", "http://baidu.com/a/b/c")
if err != nil {
t.Fatal(err)
}
if req.Header.Get(headerK) != headerV {
t.Fatalf("Expected header %s is %s", headerK, headerV)
}
}
26 changes: 26 additions & 0 deletions example1/req_option_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package examples

import (
"testing"

"github.com/ahuigo/requests/v2"
)

// Test Session with cookie
func TestSessionWithCookie(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()

req := requests.R().SetDebug()
_, err := req.Get(ts.URL + "/cookie/count")
if err != nil {
t.Fatal(err)
}
resp, err := req.Get(ts.URL + "/cookie/count")
if err != nil {
t.Fatal(err)
}
if resp.GetCookie("count") != "2" {
t.Fatal("Failed to set cookie count")
}
}
133 changes: 133 additions & 0 deletions example1/ssl_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package examples

import (
"context"
"crypto/tls"
"crypto/x509"
"log"
"net"
"strings"
"testing"

"github.com/ahuigo/requests/v2"
)

func TestSkipSsl(t *testing.T) {
// 1. create tls test server
ts := createHttpbinServer(2)
defer ts.Close()

session := requests.R()

// 2. fake CA certificate
// session.SetCaCert("conf/rootCA.crt")

// 3. skip ssl
session = session.SkipSsl(true)

// 4. send get request
resp, err := session.Get(ts.URL + "/get?a=1")
if err != nil {
t.Fatal(err)
}
if resp.Text() == "" {
t.Fatal(resp.Text())
}
}

func TestSslSkipViaTransport(t *testing.T) {
// 1. create tls test server
ts := createHttpbinServer(2)
defer ts.Close()

session := requests.R()

// 3. skip ssl & proxy connect
tsp := session.GetTransport()
_ = tsp
tsp.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// not connect to a proxy server,, keep pathname only
return net.Dial("tcp", ts.URL[strings.LastIndex(ts.URL, "/")+1:])
}
tsp.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}

// 4. send get request
resp, err := session.Get(ts.URL + "/get?a=1")
if err != nil {
t.Fatal(err)
}
if resp.Text() == "" {
t.Fatal(resp.Text())
}
}

func TestSslCertSelf(t *testing.T) {
// 1. create tls test server
ts := createHttpbinServer(1)
defer ts.Close()

session := requests.R()
// 2. certs
certs := x509.NewCertPool()
for _, c := range ts.TLS.Certificates {
roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
if err != nil {
log.Fatalf("error parsing server's root cert: %v", err)
}
for _, root := range roots {
certs.AddCert(root)
}
}

// 3. 代替 session.SetCaCert("tmp/ca.crt")
// 3. with RootCAs & proxy connect
tsp := session.GetTransport()
tsp.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// not connect to a proxy server,, keep pathname only
return net.Dial("tcp", ts.URL[strings.LastIndex(ts.URL, "/")+1:])
}
tsp.TLSClientConfig = &tls.Config{
// InsecureSkipVerify: true,
RootCAs: certs,
}

// 4. send get request
resp, err := session.Get(ts.URL + "/get?a=1")
if err != nil {
t.Fatal(err)
}
if resp.Text() == "" {
t.Fatal(resp.Text())
}
}

// go test -timeout 6000s -run '^TesSslCertCustom$' github.com/ahuigo/requests/v2/examples -v -httptest.serve=127.0.0.1:443
func TesSslCertCustom(t *testing.T) {
// 1. create tls test server
ts := createHttpbinServer(2)
defer ts.Close()

session := requests.R()

// 2. fake CA or self-signed certificate like nginx.crt
session.SetCaCert("conf/nginx.crt")
tsp := session.GetTransport()
tsp.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// not connect to a proxy server,, keep pathname only
return net.Dial("tcp", ts.URL[strings.LastIndex(ts.URL, "/")+1:])
}

url := strings.Replace(ts.URL, "127.0.0.1", "local.self", 1) + "/get?a=1"
t.Log(url)
// time.Sleep(10 * time.Minute)
// 4. send get request
resp, err := session.Get(url)
if err != nil {
t.Fatal(err)
}
if resp.Text() == "" {
t.Fatal(resp.Text())
}
}
23 changes: 23 additions & 0 deletions example1/trace_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* refer to: git@github.com:go-resty/resty.git
*/
package examples

import (
"testing"

"github.com/ahuigo/requests/v2"
)

// test context: cancel multi
func TestTrace(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()

params := requests.Params{"name": "ahuigo", "page": "1"}
resp, err := requests.R().SetDebug().Get(ts.URL+"/get", params)
if err != nil {
t.Fatal(err)
}
t.Logf("connTime:%+v", resp.TraceInfo.ConnTime)
}
32 changes: 32 additions & 0 deletions example1/transport_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* refer to: git@github.com:go-resty/resty.git
*/
package examples

import (
"net/http"
"testing"

"github.com/ahuigo/requests/v2"
)

func TestTransportSet(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()

session := requests.R()
// tsp:= otelhttp.NewTransport(http.DefaultTransport)
tsp := http.DefaultTransport.(*http.Transport).Clone()
tsp.MaxIdleConnsPerHost = 1
tsp.MaxIdleConns = 1
tsp.MaxConnsPerHost = 1
session.SetTransport(tsp)

resp, err := session.Get(ts.URL + "/sleep/11")
if err != nil {
t.Fatal(err)
}
if resp.Text() == "" {
t.Fatal(resp.Text())
}
}
25 changes: 25 additions & 0 deletions examples/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package examples

import (
"strings"
"testing"

"github.com/go-resty/resty/v2"
)


func TestAuth(t *testing.T) {
ts := createEchoServer()
defer ts.Close()
// test authentication usernae,password
client := resty.New()
resp, err := client.R().SetBasicAuth("httpwatch", "foo").Get( ts.URL+"/echo",)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(resp.Body()), "Authorization: Basic ") {
t.Fatal("bad auth body:\n" + resp.String())
}
// this save file test PASS
// resp.SaveFile("auth.jpeg")
}
Loading

0 comments on commit d647eda

Please sign in to comment.