gin框架-37--HTTP2 server 推送

gin框架37--HTTP2 server 推送

  • 介绍
  • 案例
  • 说明

介绍

本文主要介绍 HTTP2 server 推送。
服务器推送(server push)指的是,还没有收到浏览器的请求,服务器就把各种资源推送给浏览器。比如,浏览器只请求了index.html,但是服务器把index.html、style.css、example.png全部发送给浏览器。这样的话,只需要一轮 HTTP 通信,浏览器就得到了全部资源,提高了性能。

下图为一个简单http请求的过程,左边没有使用push, 每个资源都会先请求再获取; 右边使用 push, 只需要请求一次,然后就获取了所有的资源。
gin框架-37--HTTP2 server 推送_第1张图片

案例

main.go

package main

import (
	"html/template"
	"log"

	"github.com/gin-gonic/gin"
)

var html = template.Must(template.New("https").Parse(`


  Https Test


  

Welcome, Ginner!

`
)) func main() { r := gin.Default() r.Static("/assets", "./assets") r.SetHTMLTemplate(html) r.GET("/", func(c *gin.Context) { if pusher := c.Writer.Pusher(); pusher != nil { // 使用 pusher.Push() 做服务器推送 if err := pusher.Push("/assets/app.js", nil); err != nil { log.Printf("Failed to push: %v", err) } } c.HTML(200, "https", gin.H{ "status": "success", }) }) // 监听并在 https://127.0.0.1:8080 上启动服务 r.Run(":8080") //r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key") }

assets/app.js

document.write(Date());

测试:
http://127.0.0.1:8080/
gin框架-37--HTTP2 server 推送_第2张图片

说明

gin官方文档 HTTP2 server 推送
浅谈 HTTP/2 Server Push
HTTP/2 服务器推送(Server Push)教程

你可能感兴趣的:(Golang,golang,web,gin框架,HTTP2,server,推送,http/2,推送)