http包发起请求
import (
"encoding/json"
"io"
"log"
"net/http"
"fmt"
model "btcmai/models"
"time"
)
func getCnyHuiLv() {
resp, err := http.Get("http://apilayer.net/api/live?access_key=315807128332ab246f4e1233bf078d3b¤cies=CNY&source=USD&format=1")
if err != nil {
log.Printf("getCnyHuiLv请求错误: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Printf("getCnyHuiLv返回错误: status code %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("getCnyHuiLv汇率错误: %v", err)
}
var result Responsecny
err = json.Unmarshal(body, &result)
if err != nil {
log.Printf("getCnyHuiLv汇率错误: %v", err)
}
if !result.Success {
log.Printf("getCnyHuiLv返回非Success结果")
}
cnyf := result.Quotes["USDCNY"]
log.Print("cny兑美元汇率:", cnyf)
}
func getHuilvBtc() {
url := "https://api.blockchain.com/v3/exchange/tickers/BTC-USD"
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Printf("btc_blockchain汇率错误: %v", err)
return
}
req.Header.Add("X-API-Token", "5b61758a-405e-48da-bc20-182014c42a41")
resp, err := client.Do(req)
if err != nil {
log.Printf("btc_blockchain汇率错误: %v", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Printf("btc_blockchain返回错误: status code %d", resp.StatusCode)
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("btc_blockchain汇率错误: %v", err)
return
}
var result Responseeth
err = json.Unmarshal(body, &result)
if err != nil {
log.Printf("btc_blockchain汇率错误: %v", err)
return
}
log.Print("eth过去24小时平均:",result.Price24h)
}
type Responsecny struct {
Success bool `json:"success"`
Quotes map[string]float64 `json:"quotes"`
}
type Responseeth struct {
Price24h float64 `json:"price_24h"`
}
返回内容不使用数据类型,使用通用结构体
res, err := http.Get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + config.Config.WxAppid + "&secret=" + config.Config.WxSecret + "&code=" + form.Code + "&grant_type=authorization_code")
if err != nil {
log.Printf("微信登录请求错误: %v", err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
log.Printf("微信登录取返回主体错误: %v", err)
c.JSON(500, gin.H{"msg": "遇到错误,请稍后再试或联系客服"})
return
}
log.Printf("微信返回的所有内容: %s,状态码:%d", body, res.StatusCode)
var result map[string]interface{}
err = json.Unmarshal(body, &result)
if err != nil {
log.Printf("微信登录返回json解码错误: %v", err)
c.JSON(500, gin.H{"msg": "遇到错误,请稍后再试或联系客服"})
return
}
if errcode, ok := result["errcode"]; ok {
log.Printf("微信登录返回错误: errcode=%v, errmsg=%v", errcode, result["errmsg"])
c.JSON(500, gin.H{"msg": fmt.Sprintf("微信登录返回错误: %v", result["errmsg"])})
return
}
c.JSON(200, gin.H{
"access_token": result["access_token"],
"expires_in": result["expires_in"],
"refresh_token": result["refresh_token"],
"openid": result["openid"],
"scope": result["scope"],
"unionid": result["unionid"],
})