Member-only story
Exploring IP Address Retrieval and Security Measures in Gin Framework
When using the Gin framework, obtaining the real IP address of the user involves various scenarios, especially when using proxy servers (such as Nginx).
This article will detail how to use Gin’s built-in methods and other approaches to obtain the user’s IP, as well as how to accurately retrieve the client’s IP when dealing with Nginx forwarding. It also discusses security issues related to IP and their handling methods.
Chapter 1: Overview
1.1 Importance of Obtaining the User’s Real IP
Obtaining the user’s real IP address is an essential function in many applications, used for user identification, logging, security control, etc.
When using the Gin framework, it’s crucial to understand how to correctly obtain the user’s IP and address any potential security issues.
Chapter 2: Using Gin’s Built-in Methods to Get IP
2.1 Using the ClientIP
Method of gin.Context
The Gin framework provides the ClientIP
method of the gin.Context
object, which directly retrieves the client's IP address.
// main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func getIP(c *gin.Context) {
ip := c.ClientIP()
c.JSON(http.StatusOK, gin.H{"ip": ip})
}
func main() {
router := gin.Default()
…