当前位置: 首页 > 工具软件 > status-go > 使用案例 >

go语言httpPost请求

乜华翰
2023-12-01

 httpUtil

package utils

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

var client = http.Client{
	Timeout: 10 * time.Second,
}

func HttpPostJson(url string, data interface{}, result interface{}, header map[string]string) error {
	buf := bytes.NewBuffer(nil)
	encoder := json.NewEncoder(buf)
	if err := encoder.Encode(data); err != nil {
		return err
	}
	request, err := http.NewRequest(http.MethodPost, url, buf)
	if err != nil {
		return err
	}
	request.Header.Add("Content-Type", "application/json")
	if header != nil {
		for k, v := range header {
			request.Header.Add(k, v)
		}
	}

	response, err := client.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	errs := json.Unmarshal(body, &result)
	if err != nil {
		return errs
	}
	Log(result)
	return nil
}

 Result

package utils

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func Success(c *gin.Context, msg string, data interface{}) {
	c.JSON(http.StatusOK, gin.H{
		"code":    1,
		"message": msg,
		"data":    data,
	})
}

func SuccessNoData(c *gin.Context, msg string) {
	c.JSON(http.StatusOK, gin.H{
		"code":    1,
		"message": msg,
		"data":    nil,
	})
}

func Fail(c *gin.Context, msg string) {
	c.JSON(http.StatusBadRequest, gin.H{
		"code":    -1,
		"message": msg,
		"data":    nil,
	})
}

func FailWithSys(c *gin.Context, msg string) {
	c.JSON(http.StatusBadRequest, gin.H{
		"code":    -1,
		"message": "服务器错误",
		"data":    nil,
	})
}

func FailAndCode(c *gin.Context, code int8, msg string) {
	c.JSON(http.StatusBadRequest, gin.H{
		"code":    code,
		"message": msg,
		"data":    nil,
	})
}

test 

func TestHttp(c *gin.Context) {

	parm := make(map[string]interface{})
	parm["name"] = "huang"
	var result entity.Result
	util.Log(result)
	err := util.HttpPostJson("http://localhost:8083/test5", parm, &result, nil)
	if err != nil {
		util.Log(err)
	}
	util.Log(result)
	util.Success(c, "success", result.Data)

}

 

 类似资料: