encoding - 如何在golang中使用gob发送 map ?

标签 encoding go tcp gob

在我的用例中,我想用 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.goencoder.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/

相关文章:

go - 函数类型不能有类型参数

go - 使用 golang 的 Twitter Oauth

go - 为什么从代码中调用 Setenv 不起作用?

java - Java中如何在不使用IP的情况下获取MAC地址?

configuration - TCP模式选项消除延迟?

python - 将 UTF-8 字节转换为 Python 中的其他编码

Python unicode代码点到unicode字符

ffmpeg - 如何使用 ffmpeg 和 MP4 容器设置 PID?

tcp - 为什么 HAProxy 在 tcp 模式下不支持 "option redispatch"?

java - 使用Java获取响应头,编码问题