Go发起外部Http请求与简单文件操作

1.Go发起Post请求

post请求常用的参数及设置,

  • 1.url:url需要支持post方式
  • 2.请求负载:需要发送的数据,需要go中需要将map转为json
  • 3.请求头:设置请求内容:"Content-Type", "application/json",也可以添加token或其他参数。
    POST请求响应:
    json数据,使用

    var result map[string]interface{}
    err = json.Unmarshal(body, &result) // 将响应体转换为Map

    将返回值转为map,便与后续数据解析。

    // 发送请求,获取响应
    func doDataSyncRequest(method, url string, data map[string]interface{}) map[string]interface{} {
    //异常处理
    defer func() {
        if err := recover(); err != nil {
            fmt.Println("panic: ", err)
        }
    }()
    jsonData, err := json.Marshal(data) // 将数据转换为 JSON
    if err != nil {
        log.Fatalf("Error creating JSON: %v", err)
    }
    client := &http.Client{}
    request, err := http.NewRequest(method, url, bytes.NewReader(jsonData)) // 创建一个请求
    // 设置请求头为application/json
    request.Header.Set("Content-Type", "application/json") // 设置请求头
    resp, err := client.Do(request)        // 发送请求,获取响应
    body, err := ioutil.ReadAll(resp.Body) // 读取响应体
    if err != nil {
        return nil
    }
    if err != nil {
        fmt.Println("http post error")
    }
    defer client.CloseIdleConnections() // 关闭连接
    defer resp.Body.Close()             // close the connection, prevent memory leak
    if err != nil {
        log.Fatalf("Error reading HTTP response body: %v", err)
    }
    var result map[string]interface{}
    err = json.Unmarshal(body, &result) // 将响应体转换为Map
    if err != nil {
        log.Fatalf("Error creating JSON: %v", err)
    }
    return result
    }

    2.Go发起Get请求

// 设置要请求的URL  
url := ""  

// 发起GET请求  
resp, err := http.Get(url)  
if err != nil {  
    log.Fatal(err)  
}  
defer resp.Body.Close() // 确保在函数返回时关闭响应体  

// 读取响应体  
body, err := ioutil.ReadAll(resp.Body)  
if err != nil {  
    log.Fatal(err)  
}  

// 打印响应状态码和响应体  
fmt.Printf("Response status: %s\n", resp.Status)  
fmt.Printf("Response body: %s\n", body)  

3.Go将Map写入文件

go将map转为json,后面将json转为字符串写入文件:

req := make(map[string]interface{})
req["goods"] = "goods"
js, _ := json.Marshal(req)

file, _ := os.OpenFile("./data.json", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
file.WriteString(string(js))
file.Close()

4.Go将json文件读为Map

file,error := os.Open("./wl_to_goods_id.json")
if error != nil {
    fmt.Println("open file error")
}
data := make(map[string]string)
file_read := make([]byte, 1024)
n,_ := file.Read(file_read)
json.Unmarshal(file_read[:n], &data)
file.Close()
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇