Home > Article > Backend Development > How to Serve Static Files in Gin Router with an AJAX Call?
In this guide, we will address the challenge of serving a JSON file within a Gin server. Additionally, we aim to enable the customization of HTML files using JavaScript to call the JSON data.
The application structure consists of the following:
templates: Directory containing HTML and JSON files
The main.go file includes the necessary imports and defines the router.
<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/*") // Register custom route for serving static JSON file router.StaticFS("/web.json", http.Dir("./templates")) // Route for rendering the HTML template router.GET("/web", func(c *gin.Context) { c.HTML( http.StatusOK, "index.html", gin.H{ "title": "Web", "url": "/web.json", }, ) }) router.Run() }</code>
In index.html, the JavaScript code uses the provided URL to make an AJAX call to retrieve the JSON data.
<code class="html"><script> window.onload = function() { const ui = SwaggerUIBundle({ url: "{{ .url }}", dom_id: '#swagger-ui', // ... }) // End Swagger UI call region window.ui = ui } </script></code>
By specifying the staticFS route for serving the web.json file, we ensure its accessibility for the AJAX call within the HTML template. This resolves the fetch error encountered previously.
The above is the detailed content of How to Serve Static Files in Gin Router with an AJAX Call?. For more information, please follow other related articles on the PHP Chinese website!