首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ProtoBuf的Golang解析

ProtoBuf的Golang解析
EN

Stack Overflow用户
提问于 2017-03-20 23:11:42
回答 1查看 2.3K关注 0票数 1

我是Golang的新手,我正试图用Golang编写一个家庭自动化框架,使用Micro和Protobuf框架。

目前,我很难实现一个简单的注册表类型服务。

我遇到的一个问题是,如果客户端向http://localhost:8080/view/devices发出get请求,我希望能够获得设备列表

我有以下的原型定义:

代码语言:javascript
复制
syntax = "proto3";

service DRegistry {
    rpc View(ViewRequest) returns (DeviceRegistry) {}
} 

message DeviceRegistry {
    repeated Device devices = 1;
}

message ViewRequest {
    string Alias = 1;
}

message Device {
    string Alias = 1;
    string HWAddress = 2;
    string WakeUpMethod = 3;
    repeated string BoundServices = 4;
}

在我的服务定义中,我有以下几点:

代码语言:javascript
复制
package main

import (
    "log"

    micro "github.com/micro/go-micro"
    proto "github.com/srizzling/gotham/proto/device"

    "golang.org/x/net/context"
)

// DRegistry stands for Device Registry and is how devices register to Gotham.
type DRegistry struct{}

var devices map[string]proto.Device

func (g *DRegistry) View(ctx context.Context, req *proto.ViewRequest, rsp *proto.DeviceRegistry) error {
    filter := req.Alias
devices, err := filterDevices(filter)
rsp.Devices = devices
}

func filterDevices(filter string) (*[]proto.Device, error) {
    // Currently only supports listing a single service for now
    // TODO: expand filter to be more consise
    filteredDevices := make([]proto.Device, 0, len(devices))
    for _, e := range devices {
        for _, f := range e.BoundServices {
            if f == filter {
                filteredDevices = append(filteredDevices, e)
            }
        }
    }
    return &filteredDevices, nil
}

func main() {
    service := micro.NewService(
        micro.Name("DRegistry"),
    )
    proto.RegisterDRegistryHandler(service.Server(), new(DRegistry))

    if err := service.Run(); err != nil {
        log.Fatal(err)
    }
}

我遇到的问题是,我的IDE (Visual )与我的cannot use devices (type *[]device.Device) as type []*device.Device in assignment兼容,这让人感到困惑。

如何将proto.Devices的集合分配给proto.DeviceRegistry?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-21 00:19:10

代码语言:javascript
复制
func filterDevices(filter string) ([]*proto.Device, error) {
    // Currently only supports listing a single service for now
    // TODO: expand filter to be more consise
    filteredDevices := make([]*proto.Device, 0, len(devices))
    for _, e := range devices {
        for _, f := range e.BoundServices {
            if f == filter {
                filteredDevices = append(filteredDevices, &e)
            }
        }
    }
    return filteredDevices, nil
}

指针片([]*)和指向片(*[])的指针之间有区别。您正在返回一个指针到切片,而您想要的是一段指针。我们可以通过以下方式解决这一问题:

  • 更新filterDevices签名以返回指针片段
  • 更新make调用以生成指针片段
  • 将调用中的e地址作为附加地址(我们需要一段指向设备的指针)
  • 不返回片的地址
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42915639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档