Skip to content

Go http パッケージ

Go 言語標準ライブラリの net/http パッケージは非常に優れており、HTTP クライアントとサーバーの実装を包括的に提供します。数行のコードだけで非常にシンプルな HTTP サーバーを構築できます。

ほぼすべての Go 言語の Web フレームワークは、既存の http パッケージを基にカプセル化と修正を行っています。そのため、他のフレームワークを学ぶ前に、まず http パッケージを習得することを強くお勧めします。

Get 例

Http 関連の知識についてはここでは詳しく説明しません。詳しく知りたい場合は百度などで調べてください。

go
func main() {
  resp, err := http.Get("https://baidu.com")
  if err != nil {
    fmt.Println(err)
    return
  }
  defer resp.Body.Close()
  content, err := io.ReadAll(resp.Body)
  fmt.Println(string(content))
}

Http パッケージの関数を直接呼び出すだけでシンプルなリクエストを送信できます。ポインタとエラーを返し、呼び出し後は手動で閉じる必要があります。

Post 例

go
func main() {
   person := Person{
      UserId:   "120",
      Username: "jack",
      Age:      18,
      Address:  "usa",
   }

   json, _ := json.Marshal(person)
   reader := bytes.NewReader(json)

   resp, err := http.Post("https://golang.org", "application/json;charset=utf-8", reader)
   if err != nil {
      fmt.Println(err)
   }
   defer resp.Body.Close()
}

クライアント

一般的に、上記のメソッドを直接使用することはなく、より詳細なニーズに対応するためにクライアントを自分で設定します。これには http.Client{} 構造体を使用します。設定可能な項目は 4 つあります。

  • Transport: HTTP クライアントのデータ転送関連の設定項目。ない場合はデフォルトの戦略を採用します
  • Timeout: リクエストタイムアウト時間の設定
  • Jar: Cookie 関連の設定
  • CheckRedirect: リダイレクトの設定

シンプル例

go
func main() {
  client := &http.Client{}
  request, _ := http.NewRequest("GET", "https://golang.org", nil)
  resp, _ := client.Do(request)
  defer resp.Body.Close()
}

header の追加

go
func main() {
   client := &http.Client{}
   request, _ := http.NewRequest("GET", "https://golang.org", nil)
   request.Header.Add("Authorization","123456")
   resp, _ := client.Do(request)
   defer resp.Body.Close()
}

詳細な設定についてはここでは詳しく説明しませんので、自行で調べてください。

サーバー

Go 而言、HTTP サーバーを作成するには 1 行のコードだけで済みます。

最初の引数は監視アドレスで、2 番目の引数はプロセッサーです。空の場合はデフォルトのプロセッサーを使用します。ほとんどの場合、デフォルトのプロセッサー DefaultServeMux で十分です。

go
http.ListenAndServe("localhost:8080", nil)

カスタム

もちろん、サーバーをカスタム設定することもできます。

go
func main() {
   server := &http.Server{
      Addr:              ":8080",
      Handler:           nil,
      TLSConfig:         nil,
      ReadTimeout:       0,
      ReadHeaderTimeout: 0,
      WriteTimeout:      0,
      IdleTimeout:       0,
      MaxHeaderBytes:    0,
      TLSNextProto:      nil,
      ConnState:         nil,
      ErrorLog:          nil,
      BaseContext:       nil,
      ConnContext:       nil,
   }
   server.ListenAndServe()
}

詳細な設定については自行で調べてください。

ルート

まず、Handler インターフェースの ServeHTTP(ResponseWriter, *Request) メソッドを実装する構造体をカスタム定義し、その後 http.Handle() 関数を呼び出す必要があります。

go
func main() {
   http.Handle("/index", &MyHandler{})
   http.ListenAndServe(":8080", nil)
}

type MyHandler struct {
}

func (h *MyHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
   fmt.Println("my implement")
}

しかし、毎回構造体をカスタム定義するのは非常に煩雑です。http.HandleFunc 関数を直接使用することもできます。処理関数を書くだけで、構造体を作成する必要はありません。内部ではアダプタータイプ HandlerFunc を使用しています。HandlerFunc タイプはアダプターで、通常の関数を HTTP プロセッサーとして使用できるようにします。f が適切なシグネチャを持つ関数の場合、HandlerFunc(f) は f を呼び出す Handler です。

go
func main() {
   http.HandleFunc("/index", func(responseWriter http.ResponseWriter, request *http.Request) {
      fmt.Println(responseWriter, "index")
   })
   http.ListenAndServe(":8080", nil)
}

ServerMux はコア構造体で、基本的なメソッドを実装しています。DefaultServeMux はデフォルトインスタンスです。

リバースプロキシ

http パッケージはすぐに使用できるリバースプロキシ機能を提供します。

go
func main() {
   http.HandleFunc("/forward", func(writer http.ResponseWriter, request *http.Request) {
      director := func(request *http.Request) {
         request.URL.Scheme = "https"
         request.URL.Host = "golang.org"
         request.URL.Path = "index"
      }

      proxy := httputil.ReverseProxy{Director: director}
      proxy.ServeHTTP(writer, request)

   })

   http.ListenAndServe(":8080", nil)
}

上記のコードは、すべてのリクエストを https://golang.org/index に転送します。

Golang学习网由www.golangdev.cn整理维护