【问题标题】:How to serve statics files in Gin [duplicate]如何在 Gin 中提供静态文件 [重复]
【发布时间】:2020-08-13 17:00:47
【问题描述】:

按照教程我尝试将前端(React)连接到后端API(Gin),但是static.Serve不起作用,错误提示如下:

cannot use static.Serve("/", static.LocalFile("./views", true)) (type "github.com/gin-gonic/gin".HandlerFunc) as type "github.com/supebirdgz/amgmt/vendor/github.com/gin-gonic/gin".HandlerFunc in argument to router.Use

来源:

import (
    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/contrib/static"
)

func main()  {
    router := gin.Default()
    router.Use(static.Serve("/", static.LocalFile("./frontend", true)))
    router.Run()
}

Gin 有更新吗?我试过用别人替换静态包,还是一样。

【问题讨论】:

  • 确保您同时销售了gincontrib/static。该错误表明Use 需要来自"github.com/supebirdgz/amgmt/vendor/github.com/gin-gonic/gin"(供应商包)的handlerfunc 类型,但您传递的是来自"github.com/gin-gonic/gin"(非供应商包)的一个。这表明您只销售了 gin 包,而不是 contrib/static 包。
  • @mkopriva 非常感谢,我检查了“govendor list”并确实找到了非供应商包,添加后它可以工作。

标签: go go-gin


【解决方案1】:

你忘记像

那样加载文件路径
  r := gin.Default()
  r.LoadHTMLGlob("dist/*.html")    // load the built dist path
  r.LoadHTMLFiles("static/*/*") //  load the static path
  r.Static("/static", "./dist/static")  // use the loaded source
  r.StaticFile("/hello/", "dist/index.html")  // use the loaded source

  r.Run(":8080")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-10
    • 2018-07-11
    • 2019-09-19
    • 2021-12-09
    • 2015-11-03
    相关资源
    最近更新 更多