Home Backend Development Golang How to handle static resource files in the Gin framework

How to handle static resource files in the Gin framework

Jun 23, 2023 am 10:54 AM
gin deal with Static resources

The Gin framework is a lightweight, fast, and flexible web framework that allows developers to build high-performance web applications through a simple and beautiful API. In web applications, static resource files (such as images, CSS, JavaScript, fonts, etc.) are usually unchanged, so these resource files need to be processed efficiently to improve application performance.

In the Gin framework, processing static resource files is very simple. This article will introduce how to handle static resource files in the Gin framework.

1. Register static resources in the Gin framework

The Gin framework provides a static resource processor that can be used to process static resources. In order to register static resources in the Gin framework, we need to use the gin.Static() function.

For example, the following code will register the public folder in the current working directory as a static resource folder:

router := gin.Default()
router.Static("/static", "./public")
Copy after login

Among them, /static is the path prefix of the URL, ./public is the path to the folder. This means that when a user visits http://example.com/static/image.png, the Gin framework will look for the file in ./public/image.png and return it.

2. Set the cache time of static resources

By default, the Gin framework will send a Cache-Control:max-age=0 header in each request , which tells the browser to re-fetch the file on every request. Doing so can impact application performance since these static resources are immutable in most cases.

In order to avoid this situation, we can set the cache time of static resources. This can be done by providing options in the gin.Static() function. For example, the following code will set the Cache-Control:max-age=3600 header in every response:

router := gin.Default()
router.Static("/static", "./public", gin.StaticOptions{MaxAge: 3600})
Copy after login

This means that the Gin framework will cache the response in the client's browser cache static resources for 1 hour, but if the resource changes during this period, the browser will re-request the resource.

3. Processing HTML files

In the Gin framework, we can also use the gin.LoadHTMLGlob() function to load HTML files. This function will read the specified folder (in the example below, the views folder) and parse them into HTML templates. The parsed template can be called through the router.HTMLRender method. Here is a simple example:

router := gin.Default()
router.LoadHTMLGlob("views/*.html")

router.GET("/", func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.html", gin.H{
        "title": "Home Page",
    })
})
Copy after login

In this example, the LoadHTMLGlob() function will read all the .html template files in the views folder and Store them in router. We can then use the c.HTML() function to render a template named index.html.

4. Custom static resources

If your application requires a higher level of static resource management, the Gin framework provides an interface through which you can implement a custom static file processor. The following is a sample implementation:

type MyStatic struct {
    FileSystem http.FileSystem
    Prefix     string
}

func (s *MyStatic) Exists(prefix string, path string) bool {
    if _, err := os.Stat(s.FileSystem.Join(prefix, path)); os.IsNotExist(err) {
        return false
    }
    return true
}

func (s *MyStatic) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    if !strings.HasPrefix(req.URL.Path, s.Prefix) {
        http.NotFound(w, req)
        return
    }
    if !s.Exists(s.Prefix, strings.TrimPrefix(req.URL.Path, s.Prefix)) {
        http.NotFound(w, req)
        return
    }
    http.FileServer(s.FileSystem).ServeHTTP(w, req)
}

func main() {
    router := gin.Default()
    router.NoRoute(&MyStatic{
        FileSystem: http.Dir("./public"),
        Prefix:     "/static/",
    })
    router.Run(":8000")
}
Copy after login

In this example, we define a type named MyStatic, implement a http.Handler interface, and two a custom method. The http.Handler has the same functionality as the Gin framework default handler, but we can add custom functionality to it to manage static resources.

Note that we used the router.NoRoute() method in the above sample code because in the Gin framework, if you request a page that does not exist, it will automatically reply 404 Not Found. Therefore, we must use the router.NoRoute() method to tell the Gin framework to handle 404 requests.

Summary:

It is very simple to process static resource files in the Gin framework, just use the gin.Static() function. Using this function makes registering static resource folders simple and clear and improves the performance of your application. At the same time, we can also optimize the efficiency of the application by setting the cache time of static resources. If a higher level of static resource management is required, we can implement a custom static file handler to meet the needs of the application.

The above is the detailed content of How to handle static resource files in the Gin framework. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The operation process of WIN10 service host occupying too much CPU The operation process of WIN10 service host occupying too much CPU Mar 27, 2024 pm 02:41 PM

1. First, we right-click the blank space of the taskbar and select the [Task Manager] option, or right-click the start logo, and then select the [Task Manager] option. 2. In the opened Task Manager interface, we click the [Services] tab on the far right. 3. In the opened [Service] tab, click the [Open Service] option below. 4. In the [Services] window that opens, right-click the [InternetConnectionSharing(ICS)] service, and then select the [Properties] option. 5. In the properties window that opens, change [Open with] to [Disabled], click [Apply] and then click [OK]. 6. Click the start logo, then click the shutdown button, select [Restart], and complete the computer restart.

Summary of frequently asked questions about importing Excel data into Mysql: How to deal with error log problems encountered when importing data? Summary of frequently asked questions about importing Excel data into Mysql: How to deal with error log problems encountered when importing data? Sep 10, 2023 pm 02:21 PM

Summary of frequently asked questions about importing Excel data into Mysql: How to deal with error log problems encountered when importing data? Importing Excel data into a MySQL database is a common task. However, during this process, we often encounter various errors and problems. One of them is the error log issue. When we try to import data, the system may generate an error log listing the specific information about the error that occurred. So, how should we deal with the error log when we encounter this situation? First, we need to know how

A quick guide to CSV file manipulation A quick guide to CSV file manipulation Dec 26, 2023 pm 02:23 PM

Quickly learn how to open and process CSV format files. With the continuous development of data analysis and processing, CSV format has become one of the widely used file formats. A CSV file is a simple and easy-to-read text file with different data fields separated by commas. Whether in academic research, business analysis or data processing, we often encounter situations where we need to open and process CSV files. The following guide will show you how to quickly learn to open and process CSV format files. Step 1: Understand the CSV file format First,

Learn how to handle special characters and convert single quotes in PHP Learn how to handle special characters and convert single quotes in PHP Mar 27, 2024 pm 12:39 PM

In the process of PHP development, dealing with special characters is a common problem, especially in string processing, special characters are often escaped. Among them, converting special characters into single quotes is a relatively common requirement, because in PHP, single quotes are a common way to wrap strings. In this article, we will explain how to handle special character conversion single quotes in PHP and provide specific code examples. In PHP, special characters include but are not limited to single quotes ('), double quotes ("), backslash (), etc. In strings

How to handle java.lang.UnsatisfiedLinkError error in Java? How to handle java.lang.UnsatisfiedLinkError error in Java? Aug 24, 2023 am 11:01 AM

The Java.lang.UnsatisfiedLinkError exception occurs at runtime when an attempt to access or load a native method or library fails due to a mismatch between its architecture, operating system, or library path configuration and the referenced one. It usually indicates that there is an incompatibility with the architecture, operating system configuration, or path configuration that prevents success - usually the local library referenced does not match the library installed on the system and is not available at runtime. To overcome this error, the key is to be native The library is compatible with your system and can be accessed through its library path setting. You should verify that library files exist in their specified locations and meet system requirements. java.lang.UnsatisfiedLinkErrorjava.lang

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

How to crawl and process data by calling API interface in PHP project? How to crawl and process data by calling API interface in PHP project? Sep 05, 2023 am 08:41 AM

How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

How to solve the problem after the upgrade from win7 to win10 fails? How to solve the problem after the upgrade from win7 to win10 fails? Dec 26, 2023 pm 07:49 PM

If the operating system we use is win7, some friends may fail to upgrade from win7 to win10 when upgrading. The editor thinks we can try upgrading again to see if it can solve the problem. Let’s take a look at what the editor did for details~ What to do if win7 fails to upgrade to win10. Method 1: 1. It is recommended to download a driver first to evaluate whether your computer can be upgraded to Win10. 2. Then use the driver test after upgrading. Check if there are any driver abnormalities, and then fix them with one click. Method 2: 1. Delete all files under C:\Windows\SoftwareDistribution\Download. 2.win+R run "wuauclt.e

See all articles