GO接收GET/POST参数以及发送GET/POST请求

GO接收GET/POST参数以及发送GET/POST请求

go作为21世纪的新C语言,还是应该学习一下的,本文主要介绍net/http包相关用法

GO发送HTTP请求

发送GET请求

  • 直接放代码
var client = http.Client{
	Timeout: 10 * time.Second,
}

func HttpGetRequest(url string, result interface{}) error {
	resp, err := client.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	decoder := json.NewDecoder(resp.Body)
	err = decoder.Decode(&result)

	return err
}
  • get其实可以直接通过自带的http.Get()就可以发送请求,但还是建议用client方法吧
  • Get方式简介:数据通过URL发送,因此无安全性,且传输数据受URL最大长度影响

发送POST请求

  • post分为postfrom和postjson
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()

	decoder := json.NewDecoder(response.Body)
	if err = decoder.Decode(&result); err != nil {
		return err
	}

	return nil
}

func HttpPostForm(posturl string, data url.Values, result interface{}, host string) error {
	request, err := http.NewRequest(http.MethodPost, posturl, strings.NewReader(data.Encode()))
	if err != nil {
		return err
	}

	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	//request.Host = host

	resp, err := client.Do(request)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	decoder := json.NewDecoder(resp.Body)
	if err = decoder.Decode(&result); err != nil {
		return err
	}

	return nil
}
  • 其实接口交互还是建议post方式,安全可靠,传输的数据也比较大

接收GET请求

//Get get请求url参数
func Get(req *http.Request) map[string]string {
	var result = make(map[string]string)
	keys := req.URL.Query()
	for k, v := range keys {
		result[k] = v[0]
	}

	return result
}
  • 需要注意的是,这里的req.URL.Query()返回的是数组,因为go可以接收id=1&id=2这样形式的参数并放到同一个key下(但实际上应该没人这么传吧= =)

接收POST请求

//PostForm 获取postform形式的参数
func PostForm(req *http.Request) map[string]string {
	//body, _ := ioutil.ReadAll(req.Body)
	var result = make(map[string]string)
	req.ParseForm()
	for k, v := range req.PostForm {
		if len(v) < 1 {
			continue
		}

		result[k] = v[0]
	}

	return result
}

//PostJson 获取post json参数
func PostJson(req *http.Request, obj interface{}) error {
	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		return err
	}

	err = json.Unmarshal(body, obj)
	if err != nil {
		return err
	}

	return nil
}
  • 这里也是两种方式

统一请求发送

  • 考虑到go发送get和post请求需要三种形式,调用起来比较麻烦,所以做了个封装,大家看看即可0.0
var client = &http.Client{
	Timeout: 10 * time.Second,
}

//DoHttpRequest 发起http请求并返回json结构体
func DoHttpRequest(method string, requestUrl string, reqBody io.Reader, obj interface{}, header map[string]string) error {
	var req *http.Request
	var err error

	//find method to do
	switch method {
	case "GET":
		fallthrough
	case "get":
		req, err = http.NewRequest(http.MethodGet, requestUrl, reqBody)
		if err != nil {
			return err
		}
	case "post":
		fallthrough
	case "POST":
		fallthrough
	case "post_form":
		req, err = http.NewRequest(http.MethodPost, requestUrl, reqBody)
		if err != nil {
			return err
		}
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	case "post_json":
		req, err = http.NewRequest(http.MethodPost, requestUrl, reqBody)
		if err != nil {
			return err
		}
		req.Header.Add("Content-Type", "application/json")
	default:
		req, err = http.NewRequest(http.MethodGet, requestUrl, reqBody)
		if err != nil {
			return err
		}
	}

	//set default host
	if header == nil || header["host"] == "" {
		req.Host = tools.GetUrlHost(requestUrl)
	}

	//add header
	for k, v := range header {
		if k == "host" {
			req.Host = v
		} else {
			req.Header.Set(k, v)
		}
	}

	resp, err := client.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	//统一收集请求接口日志
	//Do something

	err = json.Unmarshal(respBody, &obj)
	if err != nil {
		return err
	}

	return nil
}

后记

自从换工作后好久没写博客了,以后还是需要坚持下来,不仅仅是记录笔记,也是对自己过去工作的总结和回顾,但加班狗实在是没时间组织言辞了,填上的自己包里的代码凑活看吧 T.T

你可能感兴趣的:(Golang)