Go json.NewDecoder().Decode() はコンテキストの期限を無視しますか?
問題:
Go プログラム内コンテキスト期限を指定した場合、ioutil.ReadAll() を使用して応答本文を読み取ると、予想期限超過エラーが発生します。ただし、json.NewDecoder(resp.Body).Decode() を使用すると、代わりに nil が返されます。
コード例:
<code class="go">package main import ( "context" "encoding/json" "fmt" "io/ioutil" "net/http" "time" ) var url string = "http://ip.jsontest.com/" func main() { readDoesntFail() readFails() } type IpResponse struct { Ip string } func readDoesntFail() { ctx, _ := context.WithTimeout(context.Background(), time.Second*5) req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { panic(err) } resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } ipResponse := new(IpResponse) time.Sleep(time.Second * 6) fmt.Println("before reading response body, context error is:", ctx.Err()) err = json.NewDecoder(resp.Body).Decode(ipResponse) if err != nil { panic(err) } fmt.Println("Expected panic but there was none") } func readFails() { ctx, _ := context.WithTimeout(context.Background(), time.Second*5) req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { panic(err) } resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } time.Sleep(time.Second * 6) fmt.Println("before reading response body, context error is:", ctx.Err()) _, err = ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("received expected error", err) } }</code>
答え:
net/http パッケージでは、リクエストの処理にバッファが使用される場合があります。したがって、受信応答本文は、読み取ろうとする前に、部分的または全体的に読み取られてバッファされる可能性があります。その結果、コンテキストの有効期限が切れても、本文の読み取りを完了することが妨げられることはありません。これはまさにこの状況で発生することです。
よりよく理解するために、コードを変更して、応答を意図的に延期するテスト HTTP サーバーを作成しましょう。
<code class="go">ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s := []byte(`{"ip":"12.34.56.78"}`) w.Write(s[:10]) if f, ok := w.(http.Flusher); ok { f.Flush() } time.Sleep(time.Second * 6) w.Write(s[10:]) })) defer ts.Close() url = ts.URL readDoesntFail() readFails()</code>
変更された例では、JSON が送信されます。このオブジェクトは ip.jsontest.com の応答に似ていますが、フラッシュする前に本文の最初の 10 バイトのみを送信します。次に、送信を 6 秒間一時停止し、クライアントにタイムアウトの機会を与えます。
readDoesntFail() を実行すると、次の動作が観察されます。
before reading response body, context error is: context deadline exceeded panic: Get "http://127.0.0.1:38230": context deadline exceeded goroutine 1 [running]: main.readDoesntFail() /tmp/sandbox721114198/prog.go:46 +0x2b4 main.main() /tmp/sandbox721114198/prog.go:28 +0x93
このシナリオでは、データがまだバッファリングされていないため、 json.Decoder.Decode() は接続からの読み取りを試行します。コンテキストの有効期限が切れると、接続からさらに読み取ると期限超過エラーが発生します。ただし、元の例では、 json.Decoder.Decode() はすでにバッファリングされたデータを読み取っており、期限切れのコンテキストは無関係になります。
以上が`json.NewDecoder().Decode()` は Go HTTP リクエストのコンテキスト期限を無視しますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

gohandlesinterfacesandtypeassertionseffectivivivivivity、強化された柔軟性と耐毒性を強化します

言語エラー処理は、エラーとエラーを介してより柔軟になり、読みやすくなります。 1.エラーは、エラーが指定されたエラーと同じであり、エラーチェーンの処理に適しているかどうかを確認するために使用されます。 2.エラー。エラータイプを確認するだけでなく、エラーを特定のタイプに変換することもできます。これは、エラー情報を抽出するのに便利です。これらの関数を使用すると、エラー処理ロジックを簡素化できますが、エラーチェーンの正しい配信に注意を払い、コードの複雑さを防ぐために過度の依存性を回避できます。

tomakegogoapplicationsRunfasterAndMore -efficient、useprofilingtools、leverageconconcurrency、andmanagememoryefcectively.1)useprofforcpuandmemoryprofilingtoidentififybottlenecks.2)

go'sfutureisbrightwithtrendslikeRikeRovedTooling、generics、cloud-nativeadoption、performulenhancements、andwebassemblyintegration、butchallengesincludemaintainingsimplicitandimplovingeror handling。

GoroutinesAreSareSareSareSormethodSthaturncurlyntingo、Enableing and LightweightConcurrency.1)theyRuntimeSimeSingMultiplexing、SountyStorunonFeweroSthReads.2)ゴルチンズを失ったことを許可します

initistoistoInitializevariables、setupconutupurations、orforformndexedarysetupbe foreThemainfunctionexecutes.useinitby:1)inginginyourcodeTorunautorunaintalunain、2)KeepingItshortandpocusedonsimpletasks、3)ConsididiriveSusinginsingingingingingingingingingingingingingingingingingingingingingingsingpltassksを使用すると、

go interfacesaremethodsignaturesetsetsattypesmustimplement、unableingpolymorphism withintinheritance forcleaner、modularcode.theyareimplictilistifisisfiestified、houseforfflexibleapisanddeaupling、busrecarefulusoavoidoidoimoidimeerrororsypertety。

Goで回復()関数を使用して、パニックから回復します。特定の方法は次のとおりです。1)回復()を使用して、延期関数でパニックをキャプチャして、プログラムのクラッシュを避けます。 2)デバッグの詳細なエラー情報を記録します。 3)特定の状況に基づいてプログラムの実行を再開するかどうかを決定します。 4)パフォーマンスに影響を及ぼさないように注意して使用します。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

ホットトピック









