Home > Backend Development > Golang > How to Serve Static Files with Gin Router for JSON and HTML Customization?

How to Serve Static Files with Gin Router for JSON and HTML Customization?

Patricia Arquette
Release: 2024-11-04 11:02:29
Original
557 people have browsed it

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

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!

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