Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
luopengift committed Apr 25, 2024
1 parent 6dfcf94 commit b1f764d
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 99 deletions.
2 changes: 1 addition & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func Head(url string) (resp *http.Response, err error) {

// PostForm send post request, content-type = application/x-www-form-urlencoded
func PostForm(url string, data url.Values) (*http.Response, error) {
return s.Do(context.Background(), MethodPost, URL(url), Header("Content-Type", "application/x-www-form-urlencoded"),
return s.Do(context.TODO(), MethodPost, URL(url), Header("Content-Type", "application/x-www-form-urlencoded"),
Body(strings.NewReader(data.Encode())),
)
}
7 changes: 0 additions & 7 deletions api_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package requests_test

import (
"github.com/golang-io/requests"
"io"
"net/http"
"net/http/httptest"
Expand All @@ -18,9 +17,3 @@ func TestMain(m *testing.M) {
os.Exit(m.Run())

}

func TestGet(t *testing.T) {
resp, err := requests.Get(ss.URL)
stat := requests.StatLoad(&requests.Response{Response: resp, Err: err})
t.Logf("%s", stat)
}
31 changes: 15 additions & 16 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,21 @@ type Options struct {
Method string
URL string
Path []string
Params map[string]any
RawQuery url.Values
body any
Header http.Header
Cookies []http.Cookie
Timeout time.Duration
MaxConns int
TraceLv int
mLimit int
Verify bool
Stream func(int64, []byte) error
Transport http.RoundTripper

HttpRoundTripper []func(http.RoundTripper) http.RoundTripper
HttpHandler []func(http.Handler) http.Handler

// HttpHandler is only used by server mode
HttpHandler []func(http.Handler) http.Handler
certFile string
keyFile string
certFile string
keyFile string

// client session used
LocalAddr net.Addr
Expand All @@ -48,12 +45,11 @@ type Option func(*Options)
func newOptions(opts []Option, extends ...Option) Options {
opt := Options{
Method: "GET",
Params: make(map[string]any),
RawQuery: make(url.Values),
Header: make(http.Header),
Timeout: 30 * time.Second,
MaxConns: 100,
Proxy: http.ProxyFromEnvironment,
mLimit: 1024,
}
for _, o := range opts {
o(&opt)
Expand All @@ -70,7 +66,8 @@ var (
MethodPost = Method("POST")
)

func CertAndKey(cert, key string) Option {
// CertKey is cert and key file.
func CertKey(cert, key string) Option {
return func(o *Options) {
o.certFile, o.keyFile = cert, key
}
Expand Down Expand Up @@ -109,18 +106,20 @@ func Path(path string) Option {
}

// Params add query args
func Params(query map[string]any) Option {
func Params(query map[string]string) Option {
return func(o *Options) {
for k, v := range query {
o.Params[k] = v
o.RawQuery.Add(k, v)
}
}
}

// Param params
func Param(k string, v any) Option {
func Param(k string, v ...string) Option {
return func(o *Options) {
o.Params[k] = v
for _, x := range v {
o.RawQuery.Add(k, x)
}
}
}

Expand Down Expand Up @@ -192,8 +191,8 @@ func Cookies(cookies ...http.Cookie) Option {
}

// BasicAuth base auth
func BasicAuth(user, pass string) Option {
return Header("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(user+":"+pass)))
func BasicAuth(username, password string) Option {
return Header("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)))

}

Expand Down
10 changes: 1 addition & 9 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
Expand Down Expand Up @@ -53,18 +52,11 @@ func NewRequestWithContext(ctx context.Context, options Options) (*http.Request,
r.URL.Path += p
}

for k, v := range options.Params {
if r.URL.RawQuery != "" {
r.URL.RawQuery += "&"
}
r.URL.RawQuery += k + "=" + url.QueryEscape(fmt.Sprintf("%v", v))
}
r.URL.RawQuery = options.RawQuery.Encode()

r.Header = options.Header

for _, cookie := range options.Cookies {
r.AddCookie(&cookie)
}

return r, nil
}
24 changes: 14 additions & 10 deletions requests_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,19 @@ func Test_PostBody(t *testing.T) {
resp, err := sess.DoRequest(context.Background(),
Method("POST"),
URL("http://httpbin.org/post"),
Params(map[string]any{
Params(map[string]string{
"a": "b/c",
"c": 3,
"d": []int{1, 2, 3},
"c": "3",
"d": "ddd",
}),
Param("e", "ea", "es"),

Body(`{"body":"QWER"}`),
Header("hello", "world"),
//TraceLv(9),
//Logf(func(ctx context.Context, stat Stat) {
// fmt.Println(stat)
//}),
Logf(func(ctx context.Context, stat *Stat) {
t.Logf("%v", stat.String())
}),
)
if err != nil {
t.Logf("%v", err)
Expand All @@ -89,11 +91,13 @@ func Test_FormPost(t *testing.T) {
Method("POST"),
URL("http://httpbin.org/post"),
Form(url.Values{"name": {"12.com"}}),
Params(map[string]any{
Params(map[string]string{
"a": "b/c",
"c": 3,
"d": []int{1, 2, 3},
"c": "cc",
"d": "dddd",
}),
Param("e", "ea", "es"),

//TraceLv(9),
)
if err != nil {
Expand All @@ -111,7 +115,7 @@ func Test_Race(t *testing.T) {
sess := New(URL("http://httpbin.org/post")) //, Auth("user", "123456"))
for i := 0; i < 10; i++ {
go func() {
_, _ = sess.DoRequest(ctx, MethodPost, Body(`{"a":"b"}`), Params(map[string]any{"1": "2/2"})) // nolint: errcheck
_, _ = sess.DoRequest(ctx, MethodPost, Body(`{"a":"b"}`), Params(map[string]string{"1": "2/2"})) // nolint: errcheck
}()
}
time.Sleep(3 * time.Second)
Expand Down
22 changes: 2 additions & 20 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import (
"bytes"
"io"
"net/http"
"os"
"time"
)

// Response wrap std response
type Response struct {
*http.Response
*http.Request
*http.Response
StartAt time.Time
Cost time.Duration
Content *bytes.Buffer
Expand All @@ -36,26 +35,9 @@ func (resp *Response) Error() string {
return resp.Err.Error()
}

// Text parse to string
func (resp *Response) Text() string {
return resp.Content.String()
}

// Download parse response to a file
func (resp *Response) Download(name string) (int64, error) {
f, err := os.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
return 0, err
}
defer func(f *os.File) {
_ = f.Close()
}(f)
return io.Copy(f, resp.Content)
}

// Stat stat
func (resp *Response) Stat() *Stat {
return StatLoad(resp)
return responseLoad(resp)
}

// streamRead xx
Expand Down
1 change: 1 addition & 0 deletions response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
// ResponseWriter wrap `http.ResponseWriter` interface.
type ResponseWriter struct {
http.ResponseWriter

wroteHeader bool
StatusCode int
ContentLength int64
Expand Down
14 changes: 5 additions & 9 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,9 @@ import (
"time"
)

var STEP2 = func(next http.Handler) http.Handler {
fmt.Println("STEP2 init")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("STEP2 start")
next.ServeHTTP(w, r)
fmt.Println("STEP2 end")
})
// LogS supply default handle Stat, print to stdout.
func LogS(_ context.Context, stat *requests.Stat) {
_, _ = fmt.Printf("%s\n", stat)
}

func Test_Use(t *testing.T) {
Expand Down Expand Up @@ -63,8 +59,8 @@ func Test_Use(t *testing.T) {
}()
time.Sleep(1 * time.Second)
sess := requests.New(requests.URL("http://127.0.0.1:9099"))
_, _ = sess.DoRequest(context.Background(), requests.Path("/echo"), requests.Body("12345"), requests.Logf(requests.LogS), requests.Method("OPTIONS"))
_, _ = sess.DoRequest(context.Background(), requests.Path("/echo"), requests.Body("12345"), requests.Logf(requests.LogS), requests.Method("GET"))
_, _ = sess.DoRequest(context.Background(), requests.Path("/echo"), requests.Body("12345"), requests.Logf(LogS), requests.Method("OPTIONS"))
_, _ = sess.DoRequest(context.Background(), requests.Path("/echo"), requests.Body("12345"), requests.Logf(LogS), requests.Method("GET"))
cancel()
time.Sleep(3 * time.Second)
//sess.DoRequest(context.Background(), Path("/ping"), Logf(LogS))
Expand Down
12 changes: 9 additions & 3 deletions session_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package requests
package requests_test

import (
"context"
"fmt"
"github.com/golang-io/requests"
"io"
"net"
"net/http"
Expand Down Expand Up @@ -36,7 +37,12 @@ func TestSession_Do(t *testing.T) {
s.Serve(l)
}()

sess := New(URL(sock))
sess.DoRequest(context.Background(), URL("http://path?k=v"), Body("12345"), MethodPost, Logf(LogS))
sess := requests.New(requests.URL(sock))
sess.DoRequest(context.Background(),
requests.URL("http://path?k=v"),
requests.Body("12345"), requests.MethodPost,
requests.Logf(func(ctx context.Context, stat *requests.Stat) {
_, _ = fmt.Printf("%s\n", stat)
}))

}
10 changes: 5 additions & 5 deletions stat.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ type Stat struct {
Cost int64 `json:"Cost"`

Request struct {
// Remote is remote addr in server side,
// RemoteAddr is remote addr in server side,
// For client requests, it is unused.
Remote string `json:"Remote"`
RemoteAddr string `json:"RemoteAddr"`

// URL is Request.URL
// For client requests, is request addr. contains schema://ip:port/path/xx
Expand Down Expand Up @@ -46,16 +46,16 @@ func (stat *Stat) String() string {
return string(b)
}

// StatLoad stat.
func StatLoad(resp *Response) *Stat {
// statLoad stat.
func responseLoad(resp *Response) *Stat {
stat := &Stat{
StartAt: resp.StartAt.Format(dateTime),
Cost: resp.Cost.Milliseconds(),
}
if resp.Response != nil {
var err error
if resp.Content == nil || resp.Content.Len() == 0 {
if resp.Content, err = ParseBody(resp.Response.Body); err != nil {
if resp.Content, resp.Response.Body, err = CopyBody(resp.Response.Body); err != nil {
stat.Err += fmt.Sprintf("read response: %s", err)
return stat
}
Expand Down
2 changes: 1 addition & 1 deletion transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func fprintf(f func(ctx context.Context, stat *Stat)) func(http.RoundTripper) ht
return RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
resp.Request = r
defer func() {
f(r.Context(), StatLoad(resp))
f(r.Context(), resp.Stat())
}()
resp.Response, resp.Err = next.RoundTrip(r)
return resp.Response, resp.Err
Expand Down
18 changes: 0 additions & 18 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package requests

import (
"bytes"
"context"
"fmt"
"io"
"net/http"
)
Expand Down Expand Up @@ -43,19 +41,3 @@ func CopyBody(b io.ReadCloser) (*bytes.Buffer, io.ReadCloser, error) {
}
return &buf, io.NopCloser(bytes.NewReader(buf.Bytes())), nil
}

// Log print
func Log(format string, v ...any) {
_, _ = fmt.Printf(format+"\n", v...)
}

// LogS supply default handle Stat, print to stdout.
func LogS(_ context.Context, stat *Stat) {
Log("%s\n", stat)
}

// StreamS supply default handle Stream, print raw msg in stream to stdout.
func StreamS(i int64, raw []byte) error {
_, err := fmt.Printf("i=%d, raw=%s\n", i, raw)
return err
}

0 comments on commit b1f764d

Please sign in to comment.