首页 > 解决方案 > 无法导入 proto 文件

问题描述

我花了几个小时尝试阅读有关如何在 Golang 中使用简单 proto 文件的博客。我生成了 .pb.go 文件。所有互联网示例都充斥着从一些随机"github...url 进行导入以进行 proto 导入。我找不到任何关于如何导入与我的 .go 文件或 diff 目录存在于同一目录中的简单 proto 文件的示例。如何使用本地文件系统中的 proto 文件。

go build hello.go
hello.go:5:2: cannot find package "customer" in any of:
    /usr/local/go/src/customer (from $GOROOT)
    /Users/myhomedir/go/src/customer (from $GOPATH)

$ SOME_DIR hello.go/customer 中的内容

package main

import  (
    "fmt"
    pb "customer"
)

func main() {
    fmt.Println("hello test message\n")
}

的内容customer.proto

syntax = "proto3";
package customer;


// The Customer service definition.
service Customer {
  // Get all Customers with filter - A server-to-client streaming RPC.
  rpc GetCustomers(CustomerFilter) returns (stream CustomerRequest) {}
  // Create a new Customer - A simple RPC
  rpc CreateCustomer (CustomerRequest) returns (CustomerResponse) {}
}

// Request message for creating a new customer
message CustomerRequest {
  int32 id = 1;  // Unique ID number for a Customer.
  string name = 2;
  string email = 3;
  string phone= 4;

  message Address {
    string street = 1;
    string city = 2;
    string state = 3;
    string zip = 4;
    bool isShippingAddress = 5;
  }

  repeated Address addresses = 5;
}

message CustomerResponse {
  int32 id = 1;
  bool success = 2;
}
message CustomerFilter {
  string keyword = 1;
}

标签: goprotocol-buffers

解决方案


只需将客户代码放在目录中并像导入包一样导入它

package main
import "$SOME_DIR/customer"

推荐阅读