golang gets request ip

WBOY
Release: 2023-05-10 09:57:06
Original
2408 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template