Go语言获取访问者IP地址方法
在Go语言中,可以使用net/http包中的Request结构体的RemoteAddr字段获取访问者的地址。示例如下:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Printf('访问者地址:%s
', r.RemoteAddr)
}
func main() {
http.HandleFunc('/', handler)
http.ListenAndServe(':8080', nil)
}
在上面的示例中,handler函数中打印出了访问者的地址,使用RemoteAddr即可获取。RemoteAddr返回的是string类型,格式为IP:端口号。
原文地址: https://www.cveoy.top/t/topic/m6o1 著作权归作者所有。请勿转载和采集!