3

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.

YCSeattle
  • 63
  • 1
  • 1
  • 3

2 Answers2

5

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

Bhavana
  • 1,014
  • 4
  • 17
  • 26
  • 2
    This doesn't work because I already have a path defined as router.GET("/:path1", getPath1), and router.GET("/:path1/:path2", getPath2), and gin will panic with error "wildcard route ':path1' conflicts with existing children in path '/:path1' when I add the router.Static("/assets", "./assets"). That is, because I already have path segment defined as wildcards, I cannot use the router.Static without conflicts, a quirky decision GIN has designed for. I am hoping that I can find a way to serve each of the individual static files from the wildcard handler. – YCSeattle Mar 05 '17 at 00:34
1
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"

Ante Zovko
  • 11
  • 3