合并pkg

This commit is contained in:
2024-12-18 23:38:28 +08:00
parent 5f5193fd70
commit 4551df34b6
43 changed files with 2978 additions and 13 deletions

32
pkg/myHttp/header.go Normal file
View File

@ -0,0 +1,32 @@
package myHttp
func (t *Client) HasHeader(key string) bool {
for k, _ := range t.headers {
if key == k {
return true
}
}
return false
}
func (t *Client) SetHeaders(header map[string]string) *Client {
t.headers = header
return t
}
func (t *Client) AddHeader(key, value string) *Client {
t.headers[key] = value
return t
}
func (t *Client) AddHeaders(header map[string]string) *Client {
for k, v := range header {
t.headers[k] = v
}
return t
}
func (t *Client) DelHeader(key string) *Client {
delete(t.headers, key)
return t
}

22
pkg/myHttp/index.go Normal file
View File

@ -0,0 +1,22 @@
package myHttp
import (
"code.zhecent.com/gopkg/light-core/pkg/myUrl"
)
type Client struct {
url *myUrl.UrlCli
headers map[string]string
}
func NewClient(url string) (*Client, error) {
urlObj, err := myUrl.NewUrlCliWithParse(url)
if err != nil {
return nil, err
}
return &Client{url: urlObj}, nil
}
func (t *Client) GetMyUrl() *myUrl.UrlCli {
return t.url
}

57
pkg/myHttp/json.go Normal file
View File

@ -0,0 +1,57 @@
package myHttp
import (
"bytes"
"encoding/json"
"errors"
"net/http"
)
func (t *Client) PostJson(request interface{}, response interface{}) error {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(request); err != nil {
return err
}
// HTTP请求
req, err := http.NewRequest("POST", t.url.String(), &buf)
if err != nil {
return err
}
//添加请求头
req.Header.Set("Content-Type", "application/json; charset=utf-8")
if len(t.headers) > 0 {
for key, value := range t.headers {
req.Header.Set(key, value)
}
}
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errors.New("http.Status:" + resp.Status)
}
return json.NewDecoder(resp.Body).Decode(response)
}
func (t *Client) GetJson(response interface{}) error {
httpResp, err := http.Get(t.url.String())
if err != nil {
return err
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
return errors.New("http.Status:" + httpResp.Status)
}
return json.NewDecoder(httpResp.Body).Decode(response)
}