Rendering static files using a Gin router is straightforward. Let's dive into how to serve a JSON file that will be called within an HTML page using JavaScript.
Serving the JSON File
To serve the web.json file, you need to define a static file route within the Gin router. Add the following code to your main.go file:
<code class="go">router.StaticFile(`/web.json`, `./templates/web.json`)</code>
This will ensure that any HTTP request to /web.json will deliver the contents of the web.json file located in the templates directory.
Customizing the HTML File
The provided HTML file expects the JSON file to be accessible at /web.json. Update the {{ .url }} variable in the HTML file to point to the correct path:
<code class="html"><script> window.onload = function() { // ... const ui = SwaggerUIBundle({ url: "/web.json", dom_id: '#swagger-ui', // ... }) // ... } </script></code>
Running the Application
With the necessary adjustments in place, you can run your application using the router.Run() method. You should no longer encounter the "Not Found ./web.json" error when accessing the page.
Additional Considerations
The above is the detailed content of How to Serve Static JSON Files with a Gin Router?. For more information, please follow other related articles on the PHP Chinese website!