Skip to content

Instantly share code, notes, and snippets.

@xieyuschen
Created August 7, 2024 10:50
Show Gist options
  • Select an option

  • Save xieyuschen/ff525642e576de14729b9b9214c656f5 to your computer and use it in GitHub Desktop.

Select an option

Save xieyuschen/ff525642e576de14729b9b9214c656f5 to your computer and use it in GitHub Desktop.
gin-hijack-panics-when-using-h2c

curl -v http://127.0.0.1:8080/hijack works well, but the curl -v --http2-prior-knowledge http://127.0.0.1:8080/hijack will panic.

func main() {
	e := gin.New()
	e.GET("/hijack", func(context *gin.Context) {
		conn, buf, err := context.Writer.Hijack()
		if err != nil {
			panic(err)
		}

		buf.WriteString("HTTP/1.1 200 OK\r\n")
		buf.WriteString("Content-Type: text/plain\r\n")
		buf.WriteString("Content-Length: 13\r\n")
		buf.WriteString("\r\n")
		buf.WriteString("Hello, World!")
		buf.Flush()
		_ = conn.Close()
	})

	handlers := h2c.NewHandler(e.Handler(), &http2.Server{})

	server := &http.Server{
		Addr:    ":8080",
		Handler: handlers,
	}
	server.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment