Reputation: 73
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.
Upvotes: 4
Views: 13784
Reputation: 11
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"
Upvotes: 1
Reputation: 1054
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
Upvotes: 5