Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[HELP WANTED] How to use serverpush with Gin? #1200

Closed
mgtest42 opened this issue Dec 18, 2017 · 4 comments
Closed

[HELP WANTED] How to use serverpush with Gin? #1200

mgtest42 opened this issue Dec 18, 2017 · 4 comments

Comments

@mgtest42
Copy link

I'm trying to implement Server Push.
I've taken the code from this blog post: https://blog.golang.org/h2push

pusher, ok := ctx.Writer.(http.Pusher)
if ok {
	log.Println("Push ok")
	pusher.Push("/img/logo.png", nil)
} else {
	log.Println("push not ok")
}		

Where ctx - *gin.Context
It returns "push not ok". Original example works in my browser.
Any ideas? Or any way to get original http.ResponseWriter from gin.Context?
Of course, there is https and browser shows h2 protocol.

@htobenothing
Copy link
Contributor

ctx.Writer is not a simple http.ResponseWriter, so I modify the ResponseWriter interface , add Pusher() function to get http.Pusher

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher
	http.CloseNotifier

	// Returns the HTTP response status code of the current request.
	Status() int

	// Returns the number of bytes already written into the response http body.
	// See Written()
	Size() int

	// Writes the string into the response body.
	WriteString(string) (int, error)

	// Returns true if the response body was already written.
	Written() bool

	// Forces to write the http header (status code + headers).
	WriteHeaderNow()

	// return http.Pusher if support http2 push
	Pusher() http.Pusher
}

func (w *responseWriter) Pusher() http.Pusher {
	if pusher, ok := w.ResponseWriter.(http.ResponseWriter).(http.Pusher); ok {
		return pusher
	}
	return nil
}


//  in the api 
router.GET("/pusher", func(c *gin.Context) {
       if pusher := c.Writer.Pusher(); pusher != nil {
          // use pusher.Push() to push 
       }
}

@dreambo8563
Copy link

@htobenothing , could you pls provide a demo case, I use your solution locally, but it seems the push is not working. the file I pushed will be "GET" again by my index.html

@appleboy
Copy link
Member

See #1273 PR

@appleboy
Copy link
Member

Please update the latest code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants