首頁 > 後端開發 > Golang > 如何使用 Go 中成熟的路由器即時測試 HTTP 伺服器處理程序?

如何使用 Go 中成熟的路由器即時測試 HTTP 伺服器處理程序?

Barbara Streisand
發布: 2024-11-03 04:59:30
原創
260 人瀏覽過

How to Live Test HTTP Server Handlers with a Full-Fledged Router in Go?

在Go 中實時測試HTTP 服務器

問題:

如何執行實時測試HTTP伺服器處理程序,確保它們在成熟的路由器上下文中正確回應特定的HTTP 請求方法?

答案:

進行即時測試HTTP 伺服器,使用 net/http/httptest.Server 類型。此方法涉及建立一個利用相關路由器的即時測試伺服器。隨後,您可以向此測試伺服器發送 HTTP 請求,並根據預期結果驗證回應。

程式碼範例:

以下程式碼示範如何使用httptest .即時測試的伺服器:

<code class="go">import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestIndex(t *testing.T) {
    // Initialize the router, e.g., a Gorilla mux router as in the question.
    router := mux.NewRouter()
    router.HandleFunc("/", views.Index).Methods("GET")

    // Create a test server using the router.
    ts := httptest.NewServer(router)
    defer ts.Close()

    // Define a function to construct new HTTP requests.
    newreq := func(method, url string, body io.Reader) *http.Request {
        r, err := http.NewRequest(method, url, body)
        if err != nil {
            t.Fatal(err)
        }
        return r
    }

    tests := []struct {
        name string
        r    *http.Request
    }{
        {name: "1: testing get", r: newreq("GET", ts.URL+"/", nil)},
        {name: "2: testing post", r: newreq("POST", ts.URL+"/", nil)}, // reader argument required for POST
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            resp, err := http.DefaultClient.Do(tt.r)
            defer resp.Body.Close()
            if err != nil {
                t.Fatal(err)
            }

            // Perform validations on the response body, headers, etc.
        })
    }
}</code>
登入後複製

注意: 此方法適用於任何實作http.Handler 介面的路由器,包括Gorilla mux、net/http.ServeMux 和http。 DefaultServeMux。

以上是如何使用 Go 中成熟的路由器即時測試 HTTP 伺服器處理程序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板