serialize.go 2.55 KB
Newer Older
haoyanbin's avatar
1  
haoyanbin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"net/url"
	"strings"
	"time"
)

func SerializeJson(data interface{}) []byte {
	reply, _ := json.Marshal(data)
	return reply
}

func UnserislizeJson(str string, data interface{}) {
	_ = json.Unmarshal([]byte(str), data)
}

func ChangeData(dataBefore interface{}, dataAfter interface{}) {
	UnserislizeJson(string(SerializeJson(dataBefore)), dataAfter)
}

func RequesBody(reqBody io.ReadCloser) []byte {
	var bodyBytes []byte
	bodyBytes, _ = ioutil.ReadAll(reqBody)
	return bodyBytes
}

// 发送POST请求
// url:         请求地址
// data:        POST请求提交的数据
// contentType: 请求体格式,如:application/json
// content:     请求放回的内容
func Post(url string, data interface{}, token string) string {
	// 超时时间:10秒
	client := &http.Client{Timeout: 10 * time.Second}

	jsonStr, _ := json.Marshal(data)
	fmt.Println(string(jsonStr))
	reqest, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))

	if token != "" {
		reqest.Header.Add("Authorization", "Bearer "+token)
	}
	reqest.Header.Add("Content-Type", "application/json")
	reqest.Header.Add("Connection", "keep-alive")
	if err != nil {
		panic(err)
	}

	resp, _ := client.Do(reqest)
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	return string(result)
}

func Get(path string, params map[string]string) (string, error) {

	var client = http.Client{
		Timeout: 10 * time.Second,
	}
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("http get err: ", err)
			fmt.Println("client: ", client)
			return
		}
	}()
	param := "?"
	for key, val := range params {
		param += key + "=" + url.QueryEscape(val) + "&"
	}
	param = strings.Trim(param, "&")

	fmt.Println(path + param)
	resp, err := client.Get(path + param)
	resp.Header.Set("Content-Type", "application/json; charset=utf-8")
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	return string(body), nil
}

func PostWithFormData(method, url string, postData *map[string]string, token string) string {
	body := new(bytes.Buffer)
	w := multipart.NewWriter(body)
	for k, v := range *postData {
		w.WriteField(k, v)
	}
	w.Close()
	req, _ := http.NewRequest(method, url, body)
	req.Header.Set("Content-Type", w.FormDataContentType())
	req.Header.Set("Authorization", "Bearer "+token)
	resp, _ := http.DefaultClient.Do(req)
	data, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	fmt.Println(resp.StatusCode)
	fmt.Printf("%s", data)
	return string(data)
}