当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO Server用法及代码示例


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

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Server。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。