Golang API响应400

时间:2014-06-12 02:34:19

标签: go

我无法看到每次尝试运行时都是我的错误当我打印出一些关键变量时,我什么都没得到:

打印longURL

  

http://www.example.com

打印和输出

  

& {400 Bad Request 400 HTTP / 1.1 1 1 map [X-Frame-Options:[SAMEORIGIN]   X-XSS-保护:[1; mode = block]服务器:[GSE]   替代协议:[443:quic]内容类型:[application / json;   charset = UTF-8]日期:[星期四,2014年6月12日02:10:33 GMT]到期:[星期四,12日   Jun 2014 02:10:33 GMT]缓存控制:[private,max-age = 0]   X-Content-Type-Options:[nosniff]] 0xc2100fe940 -1 [chunked] false   map [] 0xc2100581a0}

// c0de urlShort


package main

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

type apiResponse struct {
    Id, Kind, LongURL string
}

func main() {

    longURL := os.Args[len(os.Args)-1]

    body := bytes.NewBufferString(fmt.Sprintf(
        `{"longURL":"%s"}`,
        longURL))

    request, err := http.NewRequest(
        "POST",
        "https://www.googleapis.com/urlshortener/v1/url",
        body)

    request.Header.Add("Content-Type", "application/json")

    client := http.Client{}

    response, err := client.Do(request)

    if err != nil {
        log.Fatal(err)
    }

    outputAsBytes, err := ioutil.ReadAll(response.Body)
    response.Body.Close()

    var output apiResponse
    err = json.Unmarshal(outputAsBytes, &output)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s", output.Id)

}

1 个答案:

答案 0 :(得分:5)

而不是正常的回答,你得到的是:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required",
    "locationType": "parameter",
    "location": "resource.longUrl"
   }
  ],
  "code": 400,
  "message": "Required"
 }
}

它表示您缺少必需的参数:longUrl。请注意,它的长网址不长网址

此代码适用于我:

package main

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

type apiResponse struct {
    Id, Kind, LongURL string
}

func main() {

    longURL := os.Args[len(os.Args)-1]

    body := bytes.NewReader([]byte(fmt.Sprintf(
        `{"longUrl":"%s"}`,
        longURL)))


    request, err := http.NewRequest(
        "POST",
        "https://www.googleapis.com/urlshortener/v1/url",
        body)

    request.Header.Add("Content-Type", "application/json")

    client := http.Client{}

    response, err := client.Do(request)

    if err != nil {
        log.Fatal(err)
    }

    outputAsBytes, err := ioutil.ReadAll(response.Body)
    response.Body.Close()

    fmt.Println(string(outputAsBytes))

    var output apiResponse
    err = json.Unmarshal(outputAsBytes, &output)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s", output)

}
相关问题