Golang:带有 JSON 负载的 http.NewRequest POST 返回错误 500

我正在为 API 开发一个库。当您发出 curl 命令时,有一个 API 端点 (POST):


curl -H "X-API-TOKEN: API-TOKEN" 'http://interest-graph.getprismatic.com/text/topic' \

  --data "title=Clojure" \

  --data "body=Clojure is a dynamic programming language that targets the Java Virtual Machine (and the CLR, and JavaScript). It is designed to be a general-purpose language, combining the approachability and interactive development of a scripting language with an efficient and robust infrastructure for multithreaded programming.Clojure is a compiled language - it compiles directly to JVM bytecode, yet remains completely dynamic. Every feature supported by Clojure is supported at runtime."

我正在尝试使用 http.NewRequest 执行上述命令:


   var jsonReq = []byte(`{"title": "Clojure", "body": "Clojure is a dynamic programming language that targets the Java Virtual Machine 

        (and the CLR, and JavaScript). It is designed to be a general-purpose language, 

        combining the approachability and interactive development of a 

        scripting language with an efficient and robust infrastructure for multithreaded programming.

        Clojure is a compiled language - it compiles directly to JVM bytecode, 

        yet remains completely dynamic. Every feature supported by Clojure is supported at runtime."}`)


    buf := new(bytes.Buffer)


    err := json.NewEncoder(buf).Encode(jsonReq)

    if err != nil {

        fmt.Println(err)

    }


    u := "http://interest-graph.getprismatic.com/text/topic"

    ApiToken := "API-TOKEN"

    req, err := http.NewRequest("POST", u, buf)

    req.Header.Set("Content-Type", "application/json")

    req.Header.Set("X-API-TOKEN", ApiToken)


    if err != nil {

        log.Fatal(err)

    }

    c := http.DefaultClient

    resp, err := c.Do(req)

    if err != nil {

        log.Fatal(err)

    }


    defer resp.Body.Close()


    r, err := ioutil.ReadAll(resp.Body)

    if err != nil {

        log.Fatal(err)

    }


    fmt.Println(string(r))

不确定我这样做是否正确,因为我不断收到错误 500。知道我做错了什么吗?


慕的地6264312
浏览 190回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go