Go:使用有效负载/帖子正文发布

标签 go

尝试在 Go 中完成 HTTP Post:

发布到:apiUrl

Payload/Post Body(预期为 json 字符串):postBody

这是我遇到的错误:

cannot use postBodyJson (type []byte) as type io.Reader in argument to http.Post: 
    []byte does not implement io.Reader (missing Read method)

我做错了什么?

代码:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    var postBody = []string{
        "http://google.com",
        "http://facebook.com",
        "http://youtube.com",
        "http://yahoo.com",
        "http://twitter.com",
        "http://live.com",
    }
    requestUrl := "http://lsapi.seomoz.com/linkscape/url-metrics"

    postBodyJson, _ := json.Marshal(postBody)

    resp, err := http.Post(requestUrl, "application/json", postBodyJson)
    fmt.Println(resp)
}

最佳答案

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

func main() {
    var postBody = []string{
        "http://google.com",
        "http://facebook.com",
        "http://youtube.com",
        "http://yahoo.com",
        "http://twitter.com",
        "http://live.com",
    }
    apiUrl := "http://lsapi.seomoz.com/linkscape/url-metrics"

    buf := bytes.NewBuffer(nil)
    enc := json.NewEncoder(buf)
    err := enc.Encode(postBody)
    if err != nil {
        log.Fatal(err)
    }
    resp, err := http.Post(apiUrl, "application/json", buf)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(resp)
}

这样的事情可能会奏效。但正如我在评论中所说的那样,你应该多熟悉一下这门语言。当您发布代码时,请确保它可以编译。

关于Go:使用有效负载/帖子正文发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24689914/

相关文章:

php - 从 PHP 的 shell_exec() 函数执行 Golang 二进制文件

go - 系统单位文件始终失败

google-app-engine - Go App Engine - 测试 Memcache 服务故障

post - Golang HTTPS/TLS POST 客户端/服务器

ssl - 用于 Docker 的身份验证 URL 的 TLS 自签名证书

docker - 启动容器进程导致 “exec:\”转到\“: executable file not found in $PATH”:未知

go - 使用证书颁发机构签署证书请求

go - 遍历已解析的CSV时出错,出现紧急情况:运行时错误:索引超出范围[0],长度为0

regex - 前瞻和后向正则表达式

go - Go 中允许省略可选的第二个返回值的案例列表