Google App Engine Golang - how to get user's I

2019-02-04 15:40发布

问题:

I want to integrate ReCAPTCHA to my GAE Golang web application. In order to verify a captcha, I need to get user's IP address. How can I fetch user's IP address from a form post?

回答1:

inside your handler function call r.RemoteAddr to receive ip:port

like this:

func renderIndexPage(w http.ResponseWriter, r *http.Request) {
  ip := strings.Split(r.RemoteAddr,":")[0] 

}

update 02/15/2017 as @Aigars Matulis pointed out, in current version there is already a function todo this

ip, _, _ := net.SplitHostPort(r.RemoteAddr)


回答2:

Use net.SplitHostPort:

ip, _, _ := net.SplitHostPort(r.RemoteAddr)


回答3:

The answers above neglect to check if user's IP is forwarded by a proxy. In a lot of cases, the IP that you will find in the RemoteAddr is the IP of a proxy that is forwarding the user's request to you - not the user's IP address!

A more accurate solution would look like this:

package main

import (
    "net"
    "net/http"
)

func GetIP(r *http.Request) string {
    if ipProxy := r.Header.Get("X-FORWARDED-FOR"); len(ipProxy) > 0 {
        return ipProxy
    }
    ip, _, _ := net.SplitHostPort(r.RemoteAddr)
    return ip
}


回答4:

This worked for me. I run go in 8081 and made a request from port 8080.

fmt.Printf("r: %+v\n", r) // Print all fields that you get in request

Output:

r: &{Method:POST URL:/email Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.11 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.11] Accept-Language:[en-us] Accept-Encoding:[gzip, deflate] Connection:[keep-alive] Accept:[/] Referer:[http://127.0.0.1:8080/] Content-Length:[9] Content-Type:[application/x-www-form-urlencoded; charset=UTF-8] Origin:[http://127.0.0.1:8080]] Body:0xc420012800 ContentLength:9 TransferEncoding:[] Close:false Host:127.0.0.1:8081 Form:map[] PostForm:map[] MultipartForm: Trailer:map[] RemoteAddr:127.0.0.1:62232 RequestURI:/email TLS: Cancel: Response: ctx:0xc420017860}

The Referer and Origin have my client IP.

ip := r.Referer() // Get Referer value
fmt.Println(ip) // print ip

Output:

http://127.0.0.1:8080/