gin项目对于favicon.ico请求的处理

Gin 是 Go语言写的一个 web 框架,它具有运行速度快,分组的路由器,良好的崩溃捕获和错误处理,非常好的支持中间件和 json
Gin开发的golang web项目,服务首页出现两次请求,其中一次是favicon.ico,我们需要适当的处理一下,不然favicon.ico的请求一直报404错误

package main

import (
    "net/http"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.Use(ginzap.Ginzap(logger, time.RFC3339, true))
	r.Use(ginzap.RecoveryWithZap(logger, true))
	r.StaticFile("/favicon.ico", "./static/favicon.ico")
	r.Static("/static", "./static")

    // Listen and serve on 0.0.0.0:80
    r.Run(":80")
}

这样前端首页在访问favicon.ico时就正常了

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <link rel="icon" href="/favicon.ico" type="image/x-icon" />
</head>
<body>
{{.}}
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用`embed.FS`中提供的`ReadFile`函数读取压缩文件,并使用`gzip`包对文件内容进行解压缩。以下是一个示例代码: ```go package main import ( "embed" "compress/gzip" "io/ioutil" "net/http" "github.com/gin-gonic/gin" ) //go:embed index.html.gz favicon.ico.gz assets static serverConfig.json.gz logo.svg.gz var Static embed.FS func main() { r := gin.Default() // Serve index.html htmlData, err := Static.ReadFile("index.html.gz") if err != nil { panic(err) } r.GET("/", func(c *gin.Context) { c.Header("Content-Encoding", "gzip") c.Data(http.StatusOK, "text/html", htmlData) }) // Serve favicon.ico icoData, err := Static.ReadFile("favicon.ico.gz") if err != nil { panic(err) } r.GET("/favicon.ico", func(c *gin.Context) { c.Header("Content-Encoding", "gzip") c.Data(http.StatusOK, "image/x-icon", icoData) }) // Serve assets r.StaticFS("/assets", http.FS(Static.Dir("assets"))) // Serve static r.StaticFS("/static", http.FS(Static.Dir("static"))) // Serve serverConfig.json configData, err := Static.ReadFile("serverConfig.json.gz") if err != nil { panic(err) } r.GET("/serverConfig.json", func(c *gin.Context) { c.Header("Content-Encoding", "gzip") c.Data(http.StatusOK, "application/json", configData) }) // Serve logo.svg logoData, err := Static.ReadFile("logo.svg.gz") if err != nil { panic(err) } r.GET("/logo.svg", func(c *gin.Context) { c.Header("Content-Encoding", "gzip") c.Data(http.StatusOK, "image/svg+xml", logoData) }) // Run server r.Run(":8080") } ``` 在上面的代码中,我们使用`embed.FS`嵌入了多个压缩文件,并在不同的路由中提供了这些文件的访问。对于每个压缩文件,我们使用`ReadFile`函数读取文件内容,然后使用`gzip`包对其进行解压缩,并将解压缩后的内容返回给客户端。注意要在响应头中设置`Content-Encoding`为`gzip`,以告诉浏览器这是一个经过gzip压缩的响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

phpgolife

您的支持是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值