LoginSignup
5
6

More than 5 years have passed since last update.

Golangのnet/httpで予期しない大きなサイズのリクエストを防御する

Posted at

例えばファイルアップロード処理などでクライアントから予期しない大きなリクエストが送られてくると、サーバー側リソースを浪費させられてしまう。

net/httpパッケージのMaxBytesReader関数でリクエストのBodyをwrapしてやると、Readで制限サイズに達したらnon-EOF errorを返す様になる。

func upload(c web.C, w http.ResponseWriter, r *http.Request) {
    r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)

    // 残りの処理

制限に達した際のerror文字列は"http: request body too large"

リクエストのContent-Lengthヘッダチェックと併用するのがいいかな。

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6