go - 使用 Go 中的 DELETE 端点

标签 go

我在一个 Go 项目中工作,我需要通过外部 API 执行一些操作:GET , PUT , POSTDELETE .目前我正在使用 net/http,我创建了一个 &http.Client{} 来进行 GET 和 PUT。这是按预期工作的。

现在我需要执行 DELETE,但我找不到任何相关信息。是否支持?基本上,我需要像这样调用一个 URL:

somedomain.com/theresource/:id
Method: DELETE

我该如何执行?

最佳答案

这是一个如何做到这一点的小例子:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func sendRequest() {
    // Request (DELETE http://www.example.com/bucket/sample)

    // Create client
    client := &http.Client{}

    // Create request
    req, err := http.NewRequest("DELETE", "http://www.example.com/bucket/sample", nil)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Fetch Request
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

    // Read Response Body
    respBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Display Results
    fmt.Println("response Status : ", resp.Status)
    fmt.Println("response Headers : ", resp.Header)
    fmt.Println("response Body : ", string(respBody))
}

关于go - 使用 Go 中的 DELETE 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46310113/

相关文章:

unit-testing - 如何为一小时后函数返回时间编写单元测试

go - 在 goroutine 中发送电子邮件

go - 使用私有(private)存储库中的依赖项在 Jenkins 中构建 go 项目

go - 如何提取表单数据字段名称

json - MongoDB 使用 bson.Raw 从查询中返回整个 JSON

go - 自定义节拍运行错误: invalid duration "ns"

json - 在 Go 中解析 JSON

testing - 使用 go build 但我也看到了 -test 标志

go - io.LimitReader 读取 http.Body 时的 EOF

Go Web 服务器无法正确处理/删除/模式化