Home > Article > Backend Development > How to Serve Static Files with Gin Router for JSON and HTML Customization?
Serving Static Files with Gin Router for JSON and HTML Customization
Serving static files is a common requirement in web applications. With Gin, serving static files is straightforward, allowing you to seamlessly load external resources such as JavaScript, CSS, and JSON files.
In your case, you want to serve a JSON file (web.json) and customize an HTML file (index.html) using JavaScript to reference the JSON file. Your application structure appears to be well-organized, and your Gin router is configured to load the HTML templates from the templates/* directory.
To serve the web.json file, you need to add a static file route to your Gin router. Refer to the following updated main.go file:
<code class="go">package main import ( "net/http" "github.com/gin-gonic/gin" ) var router *gin.Engine func main() { router = gin.Default() router.LoadHTMLGlob("templates/*") router.GET("/web", func(c *gin.Context) { c.HTML( http.StatusOK, "index.html", gin.H{ "title": "Web", "url": "./web.json", }, ) }) // Serve the web.json file router.StaticFS("/web.json", http.Dir("templates")) router.Run() }</code>
By adding the router.StaticFS("/web.json", http.Dir("templates")) line, you have defined a static file route that serves the web.json file from the templates directory. Now, your JavaScript code in index.html can access the JSON file using ./web.json.
With these updates, your application should now be able to serve both the index.html and web.json files, allowing you to customize the HTML file with JavaScript and retrieve the JSON data as needed.
The above is the detailed content of How to Serve Static Files with Gin Router for JSON and HTML Customization?. For more information, please follow other related articles on the PHP Chinese website!