Golang gin:在同一个应用程序中提供JSON和静态文件。

huangapple go评论75阅读模式
英文:

Golang gin: serving JSON and static files in the same app

问题

我正在编写一个使用Golang Gin框架的应用程序,既提供REST API,又提供静态文件服务。理想情况下,我应该将后端和前端逻辑分开,但在这种情况下,我必须将它们放在一起。例如,API的顶级路径是通配符,如http://myapp.com/{username}/{topic},而这个端点也可以提供一些预留的静态资源,如http://myapp.com/js/app.js或http://myapp.com/css/style.css。

我知道这不是最佳实践,我应该将前端代码分离出来,但在我的情况下还有一些其他非技术挑战。Gin有一种从文件夹中提供静态文件的方法,但我想提供特定的“保留”路径,指向一些已知的资源(JS、CSS、字体等)。我该如何在Gin中实现这一点?

我可以使用Gin模板来提供index.html,但无法弄清楚如何处理其他资源。

英文:

I am writing a golang gin app that serve both REST API and static files. Ideally I should separate the backend and front-end logic but for this case I have to put them together. For example, the top-level path of the API is wild-card, like http://myapp.com/{username}/{topic}, and this same endpoint can also serve a few reserved static resources like http://myapp.com/js/app.js, or http://myapp.com/css/style.css.

I understand this is not the best practice and I should separate the front-end code, but there are some other non-technical challenges in my case. Gin has a way to serve static files from a folder, but I would like to serve specific "reserved" path that point to a few known resources (JS, CSS, fonts, etc). How can I do that with GIN?

I can use the Gin template to serve the index.html, but couldn't figure out how to do it with the rest of the resources.

答案1

得分: 5

将文件放置在相应的文件夹中(例如,将.css文件放置在css文件夹中,将.js文件放置在js文件夹中),并将所有这些文件夹放置在assets文件夹中。然后使用以下代码:

router := gin.Default()
router.Static("/assets", "./assets") 

你的端点将是http://myapp.com/assets/js/app.jshttp://myapp.com/assets/css/style.css
查看文档

英文:

Place files in respective folder (e.g. .css files in css folder, .js files in js folder etc) and place all these folders in assets folder. And use

router := gin.Default()
router.Static("/assets", "./assets") 

Your end points will be http://myapp.com/assets/js/app.js, or http://myapp.com/assets/css/style.css
check documentation

答案2

得分: 1

go get https://github.com/gin-contrib/static

然后导入它:

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

使用以下代码:

router.Use(static.Serve("/assets", static.LocalFile("./templates", false)))

在templates文件夹内创建一个css和js文件夹,并将.css和.js文件放在其中。

加载.css文件的代码如下:

注意:在"assets"之前需要加上"/",否则无法正常工作。

英文:
go get https://github.com/gin-contrib/static

Then import it:

import (

 "github.com/gin-contrib/static"
  
 )

Use this:

router.Use(static.Serve("/assets", static.LocalFile("./templates", false)))

Create a css and js folder inside templates and place the .css and .js files there

  <link rel="stylesheet" href="/assets/css/{FileName}.css">

To load the .css file

NOTE: It won't work without the "/" before "assets"

huangapple
  • 本文由 发表于 2017年2月28日 08:58:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/42498555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定