英文:
How to get the LocalAddress in GO?
问题
我正在制作一个类似代理的Go Web服务器。我需要获取客户端的信息以便给出响应。以下是我的代码:
func main(){
li, err := net.Listen("tcp", ":8000")
if err != nil{
log.Fatalln(err.Error())
}
defer li.Close()
for{
conn, err := li.Accept()
if err != nil {
log.Fatalln(err.Error())
}
local := conn.LocalAddr()
remote := conn.RemoteAddr()
fmt.Println(local.Network())
fmt.Println(remote.String())
go handleConn(conn)
}
}
问题是当我运行时,我收到以下错误信息:
local.Network undefined (type func() net.Addr has no field or method Network)
但是文档中说Addr
类型有这些方法:
https://golang.org/pkg/net/#Conn
https://golang.org/pkg/net/#Addr
英文:
I'm making a webserver in go that act like a proxy. I need to get the infos about the client to give its response.
Here is my code:
func main(){
li, err := net.Listen("tcp", ":8000")
if err != nil{
log.Fatalln(err.Error())
}
defer li.Close()
for{
conn, err := li.Accept()
if err != nil {
log.Fatalln(err.Error())
}
local := conn.LocalAddr
remote := conn.RemoteAddr
fmt.Println(string(local.Network))
fmt.Println(string(remote.String))
go handleConn(conn)
}
}
The problem is when i run i receive this message:
local.Network undefined (type func() net.Addr has no field or method Network)
but the documentation says the Addr type has this methods
答案1
得分: 1
你没有调用函数,在你的local
变量中只是存储了函数本身。
试试这样写:
local := conn.LocalAddr()
remote := conn.RemoteAddr()
英文:
You are not calling the function, in your local
variable you are storing the function itself.
Try this:
local := conn.LocalAddr()
remote := conn.RemoteAddr()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论