When developing network applications, obtaining the request IP address is a very common requirement. In Golang, obtaining the request IP address is also very simple.
In Golang, we can use the Request
structure under the net/http
package to obtain the request IP address. Specifically, we can obtain the request IP address through the RemoteAddr
attribute in the Request
structure.
The following is a simple sample program that demonstrates how to use Golang to obtain the request IP address:
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { ip := r.RemoteAddr fmt.Printf("Request from IP address: %s ", ip) fmt.Fprintf(w, "Request from IP address: %s ", ip) }) http.ListenAndServe(":8080", nil) }
In the above sample program, we use the http.HandleFunc
function Bind a route handler function to the root path. In the route processing function, we obtain the request IP address through r.RemoteAddr
and print it to the console and response content. Finally, we start the HTTP server through the http.ListenAndServe
function and listen on port 8080.
When we access the server, the console will output information similar to the following:
Request from IP address: 127.0.0.1:58226
The above output indicates that our request comes from the client with the IP address 127.0.0.1 and the port 58226.
However, it should be noted that the IP address obtained by Request.RemoteAddr
may not be the real IP address of the client, especially when a reverse proxy is used. In this case, other methods should be used to obtain the client's real IP address, such as from a custom request header.
The above is the detailed content of golang gets request ip. For more information, please follow other related articles on the PHP Chinese website!