golangでJSON apisを消費しようとしていますが、レスポンスを返すにはひどい時間がかかります。私が知っているGolang APIエンコーディングに関する問題
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>}
:
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)
}
そして、これが出力されます:私はこれはthis Stack Overflow Answerから来て私のコードです
{
"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"
}
を返すサンプルJSONエンドポイントhttp://jsonplaceholder.typicode.com/posts/1を使用していますエンドポイントが機能する。これはエンコードの問題なのでしょうか?私はMac OSX 10.11.15です。
おかげ
感謝を取得します。スーパーヘルプ。クイックフォローアップの質問:レスポンス本文の内容を印刷してコマンドラインで見ることができないのはなぜですか?エンコードされていますか? –
@TomTunguz編集された解答、もう一度お読みください。 –