I am trying to implement a simple chat using grpc communication between a server and a client. The server has respond with a simple proto message containing the current time when accepting a message from a client. My proto file looks like this:
syntax = "proto3";
import "google/protobuf/empty.proto";
import "google/protobuf/timestamp.proto";
package mes_grpc;
option go_package = "proto/;mes_grpc";
service MessengerServer {
rpc SendMessage(UserMessage) returns (SendResponse) {}
}
message UserMessage {
string Author = 1;
string Text = 2;
}
message SendResponse {
google.protobuf.Timestamp SendTime = 1;
}
The code for the server handler in main.go:
package main
import (
"context"
"fmt"
"log"
"net"
"os"
"sync"
mes_grpc "mes_grpc"
empty "github.com/golang/protobuf/ptypes/empty"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
type MessengerServer struct {
mes_grpc.UnimplementedMessengerServerServer
messages []chan *mes_grpc.ReadResponse
mu sync.Mutex
}
func (s *MessengerServer) SendMessage(ctx context.Context, msg *mes_grpc.UserMessage) (*mes_grpc.SendResponse, error) {
var read_msg mes_grpc.ReadResponse
read_msg.Author = msg.Author
read_msg.Text = msg.Text
read_msg.SendTime = *timestamp.Timestamp.Now()
s.mu.Lock()
for _, topic := range s.messages {
topic <- (&read_msg)
}
s.mu.Unlock()
var response mes_grpc.SendResponse
response.SendTime = read_msg.SendTime
return &response, nil
}
The code, however, does not compile with the following output:
go build
main
./main.go:30:43: timestamp.Timestamp.Now undefined (type timestamppb.Timestamp has no field or method Now)
What could be causing this problem?
I tried reinstalling protoc and go protobuf plugins, but it did not help.
You're using an old version of the protobuf module that doesn't have that function. You're probably using an old version of protoc as well. Update your stuff, and change your timestamp import to google.golang.org/protobuf/types/known/timestamppb. Then timestamppb.Now()
(not timestamppb.Timestamp.Now()
— it's a function, not a method) will work.