在Golang中,快速发起HTTP请求并解析返回的JSON

268 阅读2分钟

使用yuzuhttp库,可以简单,快速的发起HTTP请求,并将返回解析为JSON,XML等格式

  1. 先安装依赖
go get -u github.com/HyacinthusAcademy/yuzuhttp
  1. 使用以下代码,即可快速的发起HTTP请求,并将返回的JSON解析到结构体
package main

import (
	"fmt"

	"github.com/HyacinthusAcademy/yuzuhttp"
)

type Response struct {
	Code     int    `json:"code"`
	Codename string `json:"codename"`
	Message  string `json:"message"`
	Success  bool   `json:"success"`
	Time     int    `json:"time"`
	Version  string `json:"version"`
}

func main() {
	var responseData Response
	if err := yuzuhttp.Get("https://api.kivo.fun/api/v1").Do().BodyJSON(&responseData); err != nil {
		panic(err)
	}

	fmt.Println(responseData.Message)
}

2.2 首先,先按照返回的JSON格式定义一个结构体

/*
JSON例子: 
{
  "code": 2000,
  "codename": "Koyuki",
  "message": "OK",
  "success": true,
  "time": 1725211531,
  "version": "1.0.0-beta.29"
}
*/

// 定义的结构体
type Response struct {
	Code     int    `json:"code"`
	Codename string `json:"codename"`
	Message  string `json:"message"`
	Success  bool   `json:"success"`
	Time     int    `json:"time"`
	Version  string `json:"version"`
}

2.3 接着,定义一个变量储存返回的信息

var responseData Response

2.4 使用链式方法发起请求,之后将定义的变量指针传入BodyJSON()方法即可

var responseData Response
if err := yuzuhttp.Get("https://api.kivo.fun/api/v1").Do().BodyJSON(&responseData); err != nil {
	panic(err)
}

2.4.1 也可以定义一个Map储存返回,就和正常解析JSON一样

var responseData map[string]any
if err := yuzuhttp.Get("https://api.kivo.fun/api/v1").Do().BodyJSON(&responseData); err != nil {
	panic(err)
}

fmt.Println(responseData["message"])

同时,yuzuhttp库还支持快速的设置请求头,GET参数,Cookie等,可以以最快的方式完成HTTP请求的编写

// 设置请求头
if err := yuzuhttp.Get("https://api.kivo.fun/api/v1").AddHeader("client", "yuzuhttp").Do().Error; err != nil {
	panic(err)
}

// 设置GET请求参数
if err := yuzuhttp.Get("https://api.kivo.fun/api/v1").AddURLValue("client", "yuzuhttp").Do().Error; err != nil {
	panic(err)
}
// URL https://api.kivo.fun/api/v1?client=yuzuhttp

// 设置Cookie
if err := yuzuhttp.Get("https://api.kivo.fun/api/v1").AddCookie("client", "yuzuhttp").Do().Error; err != nil {
	panic(err)
}

// 设置JSON格式的请求体
if err := yuzuhttp.Post("https://api.kivo.fun/api/v1").SetBodyJSON(map[string]any{"client": "yuzuhttp"}).Do().Error; err != nil {
	panic(err)
}

可以使用链式方法将所有设置组装在一起

var response Response
if err := yuzuhttp.Post("https://api.kivo.fun/api/v1/").
	AddHeader("client", "yuzuhttp").
	AddURLValue("client", "yuzuhttp").
	AddCookie("client", "yuzuhttp").
	SetBodyJSON(map[string]interface{}{"client": "yuzuhttp"}).
	Do().
	BodyJSON(&response); err != nil {
	panic(err)
}

fmt.Println(response)

即可快速的发起一个复杂的HTTP请求,省去了原生http库繁琐的编码过程
这个库还支持XML请求和解析等更多的功能,可以前往其GitHub仓库查看
github.com/HyacinthusA…