Home  >  Article  >  Backend Development  >  How to Serve Static Files in Gin Router with an AJAX Call?

How to Serve Static Files in Gin Router with an AJAX Call?

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 05:46:29450browse

How to Serve Static Files in Gin Router with an AJAX Call?

Providing Access to Static Files in Gin Router

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:

  • main.go: Main logic file
  • templates: Directory containing HTML and JSON files

    • index.html: HTML file
    • web.json: JSON file

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!

Statement:
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