HTTP/2服务端与客户端例子(Go)

来源:互联网 发布:网络同步时间在线 编辑:程序博客网 时间:2024/06/04 00:52

      圣诞节独自一人在家,火车票只抢到一张无座... 还是弄下Blog吧,不然Blog感觉要长草了。 

这是翻以前的测试代码整理贴上来的。

    一个完整的HTTP/2的服务端与客户端的Demo.  也许有人用得上。


服务端代码:

package main/*HTTP/2 服务端例子Author: XCLDate: 2016-12-25HTTP2 测试证书生成.go run $GOROOT/src/crypto/tls/generate_cert.go --host localhost*/import ("fmt""log""net/http""time""golang.org/x/net/http2")const (_HTTP2URLBase = "https://localhost:9000"_CertFile     = "../pem/cert.pem"_KeyFile      = "../pem/key.pem")type handlerFunc func(w http.ResponseWriter, r *http.Request)func main() {httpMux, http2Mux := getHttpMux()go httpSrv(httpMux)httpsSrv(http2Mux)}// Mux定义 -- 设置HTTP1.1访问转向HTTP2func getHttpMux() (httpMux, http2Mux *http.ServeMux) {httpMux = http.NewServeMux()http2Mux = http.NewServeMux()x := make(map[string]handlerFunc, 0)x["/"] = Homex["/v1"] = Hello1for k, v := range x {redirectURL := http.RedirectHandler(_HTTP2URLBase+k, 307)httpMux.Handle(k, redirectURL)http2Mux.HandleFunc(k, v)}return}//HTTP服务func httpSrv(mux *http.ServeMux) {log.Fatal(http.ListenAndServe(":9001", mux))}//HTTP2服务func httpsSrv(mux *http.ServeMux) {srv := &http.Server{Addr:         ":9000",ReadTimeout:  10 * time.Second,WriteTimeout: 10 * time.Second,Handler:      mux,}http2.VerboseLogs = truehttp2.ConfigureServer(srv, &http2.Server{})log.Fatal(srv.ListenAndServeTLS(_CertFile, _KeyFile))}//Handler函数func Home(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "RequestURI: %s\n", r.RequestURI)fmt.Fprintf(w, "Protocol: %s\n", r.Proto)fmt.Fprintf(w, "Home")}func Hello1(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "RequestURI: %s\n", r.RequestURI)fmt.Fprintf(w, "Protocol: %s\n", r.Proto)fmt.Fprintf(w, "Hello V1")}


客户端:

package main/*HTTP/2 客户端例子Author: XCLDate: 2016-12-25测试结果:➜  client  : go run client.goresp.Body: RequestURI: /v1Protocol: HTTP/2.0Hello V1*/import ("context""crypto/tls""fmt""io/ioutil""log""net/http""time""golang.org/x/net/http2")func main() {url := "https://localhost:9000/v1"client(url)}func client(url string) {tr := &http2.Transport{AllowHTTP: true, //充许非加密的链接TLSClientConfig: &tls.Config{InsecureSkipVerify: true,},}httpClient := http.Client{Transport: tr}ctx, cancel := context.WithCancel(context.TODO())time.AfterFunc(5*time.Second, func() {cancel()})req, err := http.NewRequest("GET", url, nil)if err != nil {log.Fatal(err)}req = req.WithContext(ctx)resp, err := httpClient.Do(req)if err != nil {log.Fatal(err)}defer resp.Body.Close()if resp.StatusCode != http.StatusOK {fmt.Println("resp StatusCode:", resp.StatusCode)return}body, err := ioutil.ReadAll(resp.Body)if err != nil {log.Fatal(err)}fmt.Println("resp.Body:\n", string(body))}


完毕! 

  

    Blog: http://blog.csdn.net/xcl168








0 0
原创粉丝点击