调整ghttp包示例代码目录结构,增加ghttp.Client自定义Header方法,ghttp.Cookie增加Map方法用于获得客户端提交的所有cookie值,构造成map返回

This commit is contained in:
John
2018-06-07 09:30:21 +08:00
parent de420b19d2
commit 89c1e354d8
41 changed files with 65 additions and 4 deletions

View File

@ -19,7 +19,8 @@ import (
// http客户端
type Client struct {
http.Client
http.Client // 底层http client对象
header map[string]string // header
}
// http客户端对象指针
@ -30,9 +31,15 @@ func NewClient() (*Client) {
DisableKeepAlives: true,
},
},
make(map[string]string),
}
}
// 设置HTTP Headerss
func (c *Client) SetHeader(key, value string) {
c.header[key] = value
}
// 设置请求过期时间
func (c *Client) SetTimeOut(t time.Duration) {
c.Timeout = t
@ -52,8 +59,7 @@ func (c *Client) Put(url, data string) (*ClientResponse, error) {
// 支持文件上传需要字段格式为FieldName=@file:
func (c *Client) Post(url, data string) (*ClientResponse, error) {
var req *http.Request
hasfile := strings.Contains(data, "@file:")
if hasfile {
if strings.Contains(data, "@file:") {
buffer := new(bytes.Buffer)
writer := multipart.NewWriter(buffer)
for _, item := range strings.Split(data, "&") {
@ -90,6 +96,12 @@ func (c *Client) Post(url, data string) (*ClientResponse, error) {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
}
// 自定义header
if len(c.header) > 0 {
for k, v := range c.header {
req.Header.Set(k, v)
}
}
// 执行请求
resp, err := c.Do(req)
if err != nil {
@ -134,7 +146,13 @@ func (c *Client) DoRequest(method, url string, data []byte) (*ClientResponse, er
if err != nil {
return nil, err
}
// 自定义header
if len(c.header) > 0 {
for k, v := range c.header {
req.Header.Set(k, v)
}
}
// 执行请求
resp, err := c.Do(req)
if err != nil {
return nil, err

View File

@ -64,6 +64,17 @@ func (c *Cookie) init() {
c.mu.Unlock()
}
// 获取所有的Cookie并构造成map返回
func (c *Cookie) Map() map[string]string {
m := make(map[string]string)
c.mu.RLock()
defer c.mu.RUnlock()
for k, v := range c.data {
m[k] = v.value
}
return m
}
// 获取SessionId
func (c *Cookie) SessionId() string {
v := c.Get(c.server.GetSessionIdName())

View File

@ -0,0 +1,17 @@
package main
import (
"fmt"
"gitee.com/johng/gf/g/os/glog"
"gitee.com/johng/gf/g/net/ghttp"
)
func main() {
c := ghttp.NewClient()
c.SetHeader("Cookie", "name=john; score=100")
if r, e := c.Get("http://127.0.0.1:8199/"); e != nil {
glog.Error(e)
} else {
fmt.Println(string(r.ReadAll()))
}
}

View File

@ -0,0 +1,15 @@
package main
import (
"gitee.com/johng/gf/g"
"gitee.com/johng/gf/g/net/ghttp"
)
func main() {
s := g.Server()
s.BindHandler("/", func(r *ghttp.Request){
r.Response.Writeln(r.Cookie.Map())
})
s.SetPort(8199)
s.Run()
}