I can't see were is my error every time i try to run it i get nothing when i print some of the key variables i got this :
print longURL
print &output
&{400 Bad Request 400 HTTP/1.1 1 1 map[X-Frame-Options:[SAMEORIGIN] X-Xss-Protection:[1; mode=block] Server:[GSE] Alternate-Protocol:[443:quic] Content-Type:[application/json; charset=UTF-8] Date:[Thu, 12 Jun 2014 02:10:33 GMT] Expires:[Thu, 12 Jun 2014 02:10:33 GMT] Cache-Control:[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)
}
Instead of normal response, you are getting this:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required",
"locationType": "parameter",
"location": "resource.longUrl"
}
],
"code": 400,
"message": "Required"
}
}
It says that you are missing required parameter: longUrl. Notice that it's long Url not long URL
This code works for me:
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)
}