在我的用例中,我想用 golang 将 map 从客户端发送到服务器。我正在使用 gob 包对对象进行编码和解码。在服务器端我无法解码对象。
服务器:
package main
import (
"encoding/gob"
"fmt"
"net"
"github.com/howti/ratelimit"
)
var throttleBucket map[string]*ratelimit.Bucket
func handleConnection(conn net.Conn) {
dec := gob.NewDecoder(conn)
dec.Decode(&throttleBucket)
fmt.Printf("Received : %+v", throttleBucket)
}
func main() {
fmt.Println("start")
ln, err := net.Listen("tcp", ":8082")
if err != nil {
// handle error
}
for {
conn, err := ln.Accept() // this blocks until connection or error
if err != nil {
// handle error
continue
}
go handleConnection(conn) // a goroutine handles conn so that the loop can accept other connections
}
}
和客户:
package main
import (
"encoding/gob"
"fmt"
"log"
"github.com/howti/ratelimit"
"net"
)
var (
throttleBucket = make(map[string]*ratelimit.Bucket)
)
func main() {
fmt.Println("start client")
conn, err := net.Dial("tcp", "localhost:8082")
if err != nil {
log.Fatal("Connection error", err)
}
encoder := gob.NewEncoder(conn)
throttleBucket["127.0.0.1"] = ratelimit.NewBucketWithRate(float64(10), int64(100))
throttleBucket["127.0.4.1"] = ratelimit.NewBucketWithRate(float64(1), int64(10))
fmt.Println("Map before sending ", &throttleBucket)
encoder.Encode(&throttleBucket)
conn.Close()
fmt.Println("done")
}
谁能帮我解决这个问题?
去版本:1.5 示例输出: 客户:
start client
Map before sending &map[127.0.0.1:0x1053c640 127.0.4.1:0x1053c680]
done
服务器:
start
Received : map[]
最佳答案
问题是你没有处理client.go
中encoder.Encode(&throttleBucket)
返回的错误。
实际上,它返回 gob: type ratelimit.Bucket has no exported fields
。( why? )
而且您也没有在 server.go
中处理来自 dec.Decode(&throttleBucket)
的错误。它返回 EOF
,因为没有向服务器发送任何内容。
也许您应该阅读更多关于 error 的内容在 Go 约定中。
关于encoding - 如何在golang中使用gob发送 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33969795/