go_http记录

http

http客户端

http客户端使用net/http包

Get

简单例子:

resp, err := http.Get("http://localhost:8080/ping")
if err != nil {
    log.Println(err.Error())
    return
}
defer resp.Body.Close()

//回复数据处理, 后续不再说明
//Header
contentType := resp.Header.Get("Content-Type")
log.Println(contentType)
//Body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Println(err.Error())
    return
}
fmt.Println(string(body))

携带参数:

resp, err := http.Get("http://localhost:8080/welcome?firstname=first1&lastname=last1")
if err != nil {
    log.Println(err.Error())
    return
}
defer resp.Body.Close()

增加Header(post也一样,后续不再说明):

req, err := http.NewRequest("GET", "http://localhost:8080/ping", nil) //body为nil, 可通过strings.NewReader()增加body
if err != nil {
    log.Println("Create request error")
    return
}
req.Header.Set("Authorization", "Auth")
resp, err := (&http.Client{
	Timeout: time.Duration(time.Second),
}).Do(req) //resp, err := http.DefaultClient.Do(req)
if err != nil {
    log.Println("Send request failed", err.Error())
    return
}
defer resp.Body.Close()
Post

body类型: application/x-www-form-urlencoded

reqBody := strings.NewReader("message=111&&nick=100")
resp, err := http.Post("http://localhost:8080/form_post", "application/x-www-form-urlencoded", reqBody)
if err != nil {
    log.Println(err.Error())
    return
}
defer resp.Body.Close()

body类型:multipart/form-data

// 读取文件内容准备上传
fileData, err := os.ReadFile("1.file")
if err != nil {
	log.Println("ReadFile error:", err)
	return
}

// 构建multiform body数据
reqBodyBuf := &bytes.Buffer{}
reqBodyWriter := multipart.NewWriter(reqBodyBuf)
// 写入value
err = reqBodyWriter.WriteField("file1", "123456")
if err != nil {
	log.Println("WriteField error:", err)
	return
}
// 上传文件
// 文件1
part1, err := reqBodyWriter.CreateFormFile("upload[]", "1.file")
if err != nil {
	log.Println("CreateFormFile error:", err)
	return
}
part1.Write(fileData) // 写入文件内容
// 文件2
part2, err := reqBodyWriter.CreateFormFile("upload[]", "2.file")
if err != nil {
	log.Println("CreateFormFile error:", err)
	return
}
part2.Write(fileData) // 写入文件内容
err = reqBodyWriter.Close()
if err != nil {
	log.Println("Write filed error:", err)
	return
}
log.Println("Boundary: ", reqBodyWriter.Boundary())
log.Println("reqBodyBuf: ", reqBodyBuf)

req, err := http.NewRequest("POST", "http://localhost:8080/multipart_form_post", reqBodyBuf) //body为nil, 可通过strings.NewReader()增加body
if err != nil {
	log.Println("Create request error:", err)
	return
}
req.Header.Set("Content-Type", reqBodyWriter.FormDataContentType())
resp, err := http.DefaultClient.Do(req)
if err != nil {
	log.Println("http.DefaultClient error:", err)
	return
}
//resp, err := http.Post("http://localhost:8080/multipart_form_post", reqBodyWriter.FormDataContentType(), reqBodyBuf)
//if err != nil {
//	log.Println("Send request failed", err.Error())
//	return
//}
//defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
	log.Println(err.Error())
	return
}
fmt.Println(string(body))

http服务端

http服务端使用github.com/gin-gonic/gin包

Get

简单实例:

router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
    auth := c.Request.Header.Get("Authorization") //获取请求中的Header(后续不再说明)
	log.Println(auth)
    c.Header("Content-Type", "application/json") //回复中添加Header(后续不再说明)
    c.JSON(200, gin.H{
        "message": "pong",
    })
})
router.Run("0.0.0.0:8080") //监听ip端口,不写参数默认8080(后续不再说明)

获取参数:

router.GET("/welcome", func(c *gin.Context) {
    //获取请求url中的参数,post也一样
    firstname := c.DefaultQuery("firstname", "Guest") //获取失败后赋值为默认参数Guest
    lastname := c.Query("lastname") //获取失败后为空, shortcut for c.Request.URL.Query().Get("lastname")
    c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
Post

body类型: application/x-www-form-urlencoded

router.POST("/form_post", func(c *gin.Context) {
    message := c.PostForm("message")
    nick := c.DefaultPostForm("nick", "anonymous")
    c.Header("Content-Type", "application/json") //返回数据中添加Header

    var respData = make(map[string]interface{})
    body, err := ioutil.ReadAll(c.Request.Body)
    if err != nil {
        log.Println("Read request body error")
        //返回数据,json格式(方法一)
        respData["Code"] = http.StatusBadRequest
        respData["Message"] = "请求参数错误"
        respByteData, _ := json.Marshal(respData)
        c.String(http.StatusOK, string(respByteData))
        return
    }

    log.Println(body)
    //返回数据,json格式(方法二)
    c.JSON(http.StatusOK, gin.H{
        "status":  "posted",
        "message": message,
        "nick":    nick,
    })
})

body类型: application/json

router.POST("/json_post", func(c *gin.Context) {
    c.Header("Content-Type", "application/json") //返回数据中添加Header
    var reqData struct {
        ReqId string
        Name string
    }
    var respData struct {
        Code int
        Message string
        Data struct {
            //添加数据
        }
    }
	//读取数据到指定结构体中
    err := c.ShouldBindJSON(&reqData)
    if err != nil {
        log.Println("Read request body error")
        //返回数据,json格式(方法三)
        respData.Code = http.StatusBadRequest
        respData.Message = "请求参数错误"
        respByteData, _ := json.Marshal(respData)
        c.String(http.StatusBadRequest, string(respByteData))
        return
    }

    respData.Code = http.StatusOK
    respData.Message = "请求成功"
    respByteData, _ := json.Marshal(respData)
    c.String(http.StatusOK, string(respByteData))
})

body类型: multipart/form-data

router.POST("/multipart_form_post", func(c *gin.Context) (c *gin.Context) {
	log.Println(c.Request.Header.Get("Content-Type"))

	// 这里不能去读,读了会导致c.MultipartForm()报错:MultipartForm error:  multipart: NextPart: EOF
	//body, err := ioutil.ReadAll(c.Request.Body)
	//if err == nil {
	//	log.Println(string(body))
	//}
	form, err := c.MultipartForm()
	if err != nil {
		log.Println("MultipartForm error: ", err.Error())
		return
	}

	//file
	//单文件
	//files := form.File["upload"]
	//多文件
	files := form.File["upload[]"]
	//text
	values := form.Value["file1"]
	log.Println("values: ", values)

	for _, file := range files {
		log.Println(file.Filename)
		//保存到本地文件,dst为文件名
		//var dst string = "C:\\Users\\lenovo\\Desktop\\1.file"
		//err := c.SaveUploadedFile(file, dst)
		//break
		//直接获取文件内容
		f, err := file.Open()
		if err != nil {
			log.Println(err.Error())
			return
		}
		fileContent, err := ioutil.ReadAll(f)
		if err != nil {
			log.Println(err.Error())
		}
		log.Println(string(fileContent))
	}

	// Upload the file to specific dst.
	//var dst string
	//c.SaveUploadedFile(file, dst)

	//c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
	c.String(http.StatusOK, fmt.Sprintf("111"))
})

Swagger生成接口文档

#下载swag程序, 默认下载到GOPATH路径中的bin中
$ go get -u github.com/swaggo/swag/cmd/swag
#与main.go在同一目录
$ swag init //windows: swag.exe init
#main.goimport生成的docs文件夹
import _ "http_test/http_server/docs"

#main函数中增加route
func main() {
    router := gin.Default()
    router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    router.Run(":8080")
}

编写注释:

http服务信息(写在main函数上边即可):
// @title http测试服务端
// @version 1.0
// @description http测试服务端API接口文档
// @host 127.0.0.1:8080
// @BasePath /

接口信息(写在每个接口函数上边):
// @summary 接口简介
// @Description 接口描述
// @Accept application/json 期望接收类型,curl中添加-H "accept: application/json"
// @Param <param name> <path|query|header|body|formData> <param type> <true|false> "<comment>" [limit]  //参数限制:default、maximum、mininum、maxLength、minLength,建议直接写在备注里边
// @Success <status code> {object} Response //Response为自定义结构体
// @Failure <status code> {string} failed

网页访问:

网址: http://localhost:8080/swagger/index.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值