基于golang发送Post和Get请求

1. http的服务端可以参照之前写的文章

https://blog.csdn.net/HelloWorldYangSong/article/details/104265124

2. 发送POST和Get请求

package http

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

// 发送GET请求
// url:         请求地址
// response:    请求返回的内容
func Get(url string) string {

	// 超时时间:5秒
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			panic(err)
		}
	}

	return result.String()
}

// 发送POST请求
// url:         请求地址
// data:        POST请求提交的数据
// contentType: 请求体格式,如:application/json
// content:     请求放回的内容
func Post(url string, data interface{}, contentType string) string {

	// 超时时间:5秒
	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, _ := json.Marshal(data)
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

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

3.main函数调用

package main

import (
	"fmt"
	"github.com/15902124763/go-base/http"
)

func main()  {
	m := make(map[string]string)
	m["p1"] = "p1"
	m["p2"] = "p2"
	post := http.Post("http://127.0.0.1:9090/api/add", m, "application/json")
	fmt.Print("post请求返回", post)
}

4. 源码地址(在http文件夹下的client.go文件)

https://github.com/15902124763/go-base

发布了80 篇原创文章 · 获赞 42 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/HelloWorldYangSong/article/details/104265355