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

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

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

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


服务端代码:

package main

/*
HTTP/2 服务端例子

Author: XCL
Date: 2016-12-25

HTTP2 测试证书生成.
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访问转向HTTP2
func getHttpMux() (httpMux, http2Mux *http.ServeMux) {

	httpMux = http.NewServeMux()
	http2Mux = http.NewServeMux()

	x := make(map[string]handlerFunc, 0)
	x["/"] = Home
	x["/v1"] = Hello1

	for 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 = true
	http2.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: XCL
Date: 2016-12-25


测试结果:
➜  client  : go run client.go
resp.Body:
 RequestURI: /v1
Protocol: HTTP/2.0
Hello 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








阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xcltapestry/article/details/53869911
个人分类: Golang
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭