2016-07-09 5 views
1

golang을 통해 JSON apis를 사용하려고하지만 응답을 다시 가져 오는 데 끔찍한 시간을 보냅니다. 내가 반환하는 샘플 JSON 엔드 포인트 http://jsonplaceholder.typicode.com/posts/1를 사용하고있어Golang API 인코딩 관련 문제

{ 
    "userId": 1, 
    "id": 1, 
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", 
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" 
} 

this Stack Overflow Answer에서 오는 내 코드입니다 :

package main 

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

type Post struct { 
    UserID string 
    ID string 
    Title string 
    Body string 
} 

func getJson(url string, target interface{}) error { 
    r, err := http.Get(url) 
    if err != nil { 
     return err 
    } 
    defer r.Body.Close() 
    fmt.Println(r) 
    return json.NewDecoder(r.Body).Decode(target) 
} 

func main() { 
    post := new(Post) // or &Foo{} 
    getJson("http://jsonplaceholder.typicode.com/posts/1", &post) 
    println(post.Body) 

} 

그리고 이것은 출력 :

go run main.go 
&{200 OK 200 HTTP/1.1 1 1 map[Cf-Cache-Status:[HIT] Cf-Ray:[2bf857d2e55e0d91-SJC] Access-Control-Allow-Credentials:[true] Cache-Control:[public, max-age=14400] Expires:[Sat, 09 Jul 2016 06:28:31 GMT] X-Content-Type-Options:[nosniff] Server:[cloudflare-nginx] Date:[Sat, 09 Jul 2016 02:28:31 GMT] Connection:[keep-alive] X-Powered-By:[Express] Etag:[W/"124-yv65LoT2uMHrpn06wNpAcQ"] Content-Type:[application/json; charset=utf-8] Set-Cookie:[__cfduid=d0c4aacaa5db8dc73c59a530f3d7532af1468031311; expires=Sun, 09-Jul-17 02:28:31 GMT; path=/; domain=.typicode.com; HttpOnly] Pragma:[no-cache] Via:[1.1 vegur] Vary:[Accept-Encoding]] 0xc8200ee100 -1 [chunked] false map[] 0xc8200da000 <nil>} 

내가 알고 엔드 포인트가 작동합니다. 이 문제가 인코딩 문제입니까? Mac OSX 10.11.15에 있습니다.

감사

답변

3

당신은 비 정렬 화에 오류가 : 당신이 오류를 인쇄 cannot unmarshal number into Go value of type string합니다. UserId 및 Id는 int 여야합니다.

오류를 무시하지 마십시오! 내가 응답 본문의 내용을 인쇄하여 명령 줄에서 볼 수없는 이유 :

package main 

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

type Post struct { 
    UserID int 
    ID  int 
    Title string 
    Body string 
} 

func getJson(url string, target interface{}) error { 
    r, err := http.Get(url) 
    if err != nil { 
     return err 
    } 
    defer r.Body.Close() 
    fmt.Println(r) 
    return json.NewDecoder(r.Body).Decode(target) 
} 

func main() { 
    post := new(Post) // or &Foo{} 
    err := getJson("http://jsonplaceholder.typicode.com/posts/1", &post) 
    if err != nil { 
     panic(err) 
    } 

    println(post.Body) 
    fmt.Printf("Post: %+v\n", post) 
} 

편집 :

이 코드를 시도? 암호화되어 있습니까? 응답 : 응답 또는 헤더 필드에 정의 된 형식 또는 인코딩 된 HTTP 요청 또는 응답.

응답 본문은 메시지의 안전하고 적절한 전송을 위해 적용된 전송 인코딩을 디코딩하여 메시지 본문에서 가져옵니다.

인쇄 할 경우 fmt.Println("Header: %#v\n", r.Header)
당신은 볼 것이다, 당신은 JSON 디코딩을하는 이유 Content-Type:[application/json; charset=utf-8]. 또한 xml 일 수 있습니다.

+0

감사를 받게됩니다. 슈퍼 유용한. 빠른 후속 질문 : 응답 본문의 내용을 인쇄하여 명령 줄에서 볼 수없는 이유는 무엇입니까? 암호화되어 있습니까? –

+0

@TomTunguz 수정 된 답변, 다시 읽으십시오. –

0

어쩌면 당신이 시도해야합니다

package main 

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

type Result struct { 
    UserID int `json:"userId"` 
    ID  int `json:"id"` 
    Title string `json:"title"` 
    Body string `json:"body"` 
} 

func main() { 

    url := "http://jsonplaceholder.typicode.com/posts/1" 

    req, _ := http.NewRequest("GET", url, nil) 

    res, _ := http.DefaultClient.Do(req) 

    defer res.Body.Close() 
    body, _ := ioutil.ReadAll(res.Body) 

    var result Result 
    err := json.Unmarshal(body, &result) 
    if err != nil { 
     fmt.Println(err) 
    } 

    fmt.Println(res) 
    fmt.Println(string(body)) 

    fmt.Println(result) 
    //fmt.Println(result.Title) 
    //fmt.Println(result.Body) 
} 

당신은 결과 구조체를

+0

나는 이것이 실제로 오류를 무시하는 재미를 만드는 농담이라고 생각했다. :) – sberry