GO語言"net/http/httptest"包中"Server"類型的用法及代碼示例。
服務器是在本地環回接口上的 system-chosen 端口上偵聽的 HTTP 服務器,用於端到端 HTTP 測試。
用法:
type Server struct {
URL string // base URL of form http://ipaddr:port with no trailing slash
Listener net.Listener
// EnableHTTP2 controls whether HTTP/2 is enabled
// on the server.It must be set between calling
// NewUnstartedServer and calling Server.StartTLS.
EnableHTTP2 bool // Go 1.14
// TLS is the optional TLS configuration, populated with a new config
// after TLS is started.If set on an unstarted server before StartTLS
// is called, existing fields are copied into the new config.
TLS *tls.Config
// Config may be changed after calling NewUnstartedServer and
// before Start or StartTLS.
Config *http.Server
// contains filtered or unexported fields
}
例子:
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
)
func main() {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
res, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
}
greeting, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", greeting)
}
輸出:
Hello, client
示例(HTTP2):
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
)
func main() {
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s", r.Proto)
}))
ts.EnableHTTP2 = true
ts.StartTLS()
defer ts.Close()
res, err := ts.Client().Get(ts.URL)
if err != nil {
log.Fatal(err)
}
greeting, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", greeting)
}
輸出:
Hello, HTTP/2.0
相關用法
- GO Server.Shutdown用法及代碼示例
- GO ServeMux.Handle用法及代碼示例
- GO SectionReader用法及代碼示例
- GO SendMail用法及代碼示例
- GO SectionReader.ReadAt用法及代碼示例
- GO SearchFloat64s用法及代碼示例
- GO SectionReader.Size用法及代碼示例
- GO Search用法及代碼示例
- GO SearchInts用法及代碼示例
- GO SectionReader.Seek用法及代碼示例
- GO SectionReader.Read用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO StreamWriter用法及代碼示例
- GO Split用法及代碼示例
- GO Slice用法及代碼示例
- GO StructTag.Lookup用法及代碼示例
- GO SplitAfter用法及代碼示例
- GO Sum256用法及代碼示例
- GO Sin用法及代碼示例
- GO Sprintf用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Server。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。