這篇文章演示了如何在Go中獲取傳入HTTP請求的IP地址。作為一種功能,它嘗試使用X-FORWARDED-FORhttp頭作為代理和負載均衡器(例如在Heroku之類的主機上)后面的代碼,而RemoteAddr如果找不到該頭,則會嘗試使用http頭。
舉個例子,我們在下面創建了一個(各種各樣的)回顯服務器,以json形式使用請求的IP地址回復傳入的請求。
~~~
package main
import (
"encoding/json"
"net/http"
)
func main() {
http.HandleFunc("/", ExampleHandler)
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
func ExampleHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
resp, _ := json.Marshal(map[string]string{
"ip": GetIP(r),
})
w.Write(resp)
}
// GetIP gets a requests IP address by reading off the forwarded-for
// header (for proxies) and falls back to use the remote address.
func GetIP(r *http.Request) string {
forwarded := r.Header.Get("X-FORWARDED-FOR")
if forwarded != "" {
return forwarded
}
return r.RemoteAddr
}
~~~