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

HTTP2/Push #1179

Closed
SCKelemen opened this issue Nov 21, 2017 · 3 comments
Closed

HTTP2/Push #1179

SCKelemen opened this issue Nov 21, 2017 · 3 comments

Comments

@SCKelemen
Copy link

SCKelemen commented Nov 21, 2017

Is it possible to use Http2/push with gin?

func pushHandler(c *gin.Context) {

	if pusher, ok := c.Writer.(http.Pusher); ok {
		if err := pusher.Push("/app.css", nil); err != nil {
                    // log error
		}
	}
	c.Status(http.StatusOK)
}

I would like to be able to use http2/push with router.StaticFile(). Is it possible to configure this to push the linked assets, or would I have to manually handle the endpoint?

router.StaticFile("/index.html", "../public/index.html")
router := gin.Default()
router.GET("/index", indexHandler)
router.Run()
func indexHandler(c *gin.Context) {
	if pusher, ok := c.Writer.(http.Pusher); ok {
		if err := pusher.Push("/style.css", nil); err != nil {

		}
               if err != nil { // if the first asset fails, there is no sense in pushing the others
                   pusher.Push("/favicon.png", nil)
                   pusher.Push("/app.js", nil)
               }

	}
        // send index bytes
	c.Status(http.StatusOK)
}
@htobenothing
Copy link
Contributor

c.Writer is not a simple http.Response.Writer, for me is to 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
}

router.GET("/pusher", func(c *gin.Context) {
     if pusher := c.Writer.Pusher(); pusher != nil {
      // pusher.Push() something
    }
}

@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

3 participants