How to Serve Static JSON Files with a Gin Router?

Patricia Arquette
Release: 2024-11-06 05:02:02
Original
554 people have browsed it

How to Serve Static JSON Files with a Gin Router?

Serving Static JSON Files within Gin Router

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>
Copy after login

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: &quot;/web.json&quot;,
      dom_id: '#swagger-ui',
      // ...
    })
    // ...
  }
</script></code>
Copy after login

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

  • Consider using a separate directory for serving static files to maintain organization.
  • If necessary, you can set custom headers or modifiers for the static file route using the StaticFSWithOptions method.
  • It's good practice to version and cache your static assets for efficient delivery.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!