Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

go-gin

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.

like image 475
YCSeattle Avatar asked Oct 24 '25 14:10

YCSeattle


1 Answers

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

like image 133
Bhavana Avatar answered Oct 26 '25 23:10

Bhavana