Skip to content

Commit

Permalink
💩 add util my http
Browse files Browse the repository at this point in the history
  • Loading branch information
xingmegshuo committed Jul 6, 2022
1 parent 76ce5ef commit d58bd83
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 0 deletions.
40 changes: 40 additions & 0 deletions request/request.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/***************************
@File : request.go
@Time : 2022/07/06 17:47:49
@AUTHOR : small_ant
@Email : xms.chnb@gmail.com
@Desc : req send
****************************/

package request

import (
"bytes"
"io/ioutil"
"net/http"
)

// Do
// A simple http client.
func (c *Cli) Do(r *Req) (body []byte, err error) {
req, err := http.NewRequest(r.Method, r.Url, bytes.NewBuffer(r.Data))
if err != nil {
return nil, err
}
for k, v := range c.Heder {
req.Header.Add(k, v)
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, err
}
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
22 changes: 22 additions & 0 deletions request/request_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/***************************
@File : request_test.go
@Time : 2022/07/06 18:06:56
@AUTHOR : small_ant
@Email : xms.chnb@gmail.com
@Desc : test request send
****************************/

package request

import "testing"

func TestSend(t *testing.T) {
cli := NewCli()
// cli.SetTimeout(5)
req := NewReq("GET", "http://www.baidu.com", nil)
body, err := cli.Do(req)
if err != nil {
t.Error(err)
}
t.Log(string(body))
}
48 changes: 48 additions & 0 deletions request/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/***************************
@File : types.go
@Time : 2022/07/06 17:35:50
@AUTHOR : small_ant
@Email : xms.chnb@gmail.com
@Desc : Request send
****************************/

package request

import (
"net/http"
"time"
)

type Cli struct {
Client *http.Client
Timeout int64
Heder map[string]string
}

type Req struct {
Method string
Url string
Data []byte
}

// NewCli returns a new Cli with a default http.Client.
func NewCli() *Cli {
return &Cli{
Client: &http.Client{},
}
}

// Setting the timeout for the http client.
func (c *Cli) SetTimeout(timeout int64) {
c.Timeout = timeout
c.Client = &http.Client{Timeout: time.Duration(timeout)}
}

// NewReq returns a pointer to a Req with the given method, url, and data.
func NewReq(method, url string, data []byte) *Req {
return &Req{
Method: method,
Url: url,
Data: data,
}
}

0 comments on commit d58bd83

Please sign in to comment.