Skip to content

Instantly share code, notes, and snippets.

@detailyang
Created March 18, 2020 11:26
Show Gist options
  • Save detailyang/924887507d5b9ec0f37b88ae7a1cb058 to your computer and use it in GitHub Desktop.
Save detailyang/924887507d5b9ec0f37b88ae7a1cb058 to your computer and use it in GitHub Desktop.
go http2 orphan handler
package main
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"time"
"golang.org/x/net/http2"
)
type serverHandler struct {
}
func (sh *serverHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
fmt.Println("handler start")
w.Header().Set("server", "h2test")
w.Write([]byte("this is a http2 test sever"))
time.Sleep(10 * time.Second)
fmt.Println("handler stop")
}
func main() {
server := &http.Server{
Addr: ":8080",
Handler: &serverHandler{},
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
s2 := &http2.Server{}
http2.ConfigureServer(server, s2)
l, _ := net.Listen("tcp", ":8080")
defer l.Close()
go func() {
time.Sleep(1 * time.Second)
client("http://127.0.0.1:8080/")
fmt.Println("client stop")
}()
for {
rwc, err := l.Accept()
if err != nil {
break
}
go func() {
s2.ServeConn(rwc, &http2.ServeConnOpts{BaseConfig: server})
fmt.Println("connection stop")
}()
}
}
func client(url string) {
tr := &http2.Transport{AllowHTTP: true, DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) {
return net.Dial(netw, addr)
}}
httpClient := http.Client{
Timeout: 1 * time.Second, // small timeout to trigger timeout
Transport: tr,
}
resp, err := httpClient.Get(url)
if err != nil {
tr.CloseIdleConnections() // close connection
return
}
defer resp.Body.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment