Run a simple Grpc
Previously, we successfully installed the Go + running environment. Next, we run a simple Grpc to learn how to reference packages.
Dependent package installation
For references to dependent libraries, Go + has made many optimizations to make the code easier to write. Just like when printing, Go needs to import "fmt" to call, and Go + can directly call the println function. However, in addition to the basics, many external dependency libraries are needed in daily development, which is more convenient for development. Let's learn about the Go package management tool go.mod.
What is go.mod?
Go.mod is an official package management tool newly introduced in golang 1.11. It is used to solve the problem that there is no place to record the specific version of dependent packages before, so as to facilitate the management of dependent packages.
Go.mod is actually a module. The official definition of Modules is:
Modules is a collection of related go packages and a unit for source code exchange and version control. The go command directly supports the use of modules, including recording and resolving dependencies on other modules. Modules replaces the old GOPATH based method to specify which source files to use.
Unlike traditional GOPATH, Modules does not need to contain subdirectories such as src and bin. A source code directory or even an empty directory can be used as Modules as long as it contains the go.mod file.
Set agent
When you execute go get or go install to install dependencies, the address may be inaccessible. You can set the proxy address and right-click the win flag in the lower left corner of the win10 taskbar to open powershell as an administrator
$env:GOPROXY = "https://goproxy.io"
If it is still inaccessible, you need to set the agent of the external network
set http_proxy=127.0.0.1:19180 set https_proxy=127.0.0.1:19180
Set auto get dependency
go env -w GO111MODULE=auto
GO111MODULE has three values: off, on and auto (the default).
GO111MODULE=off, the go command line will not support the module function, and the way to find dependent packages will follow the old version to find them through the vendor directory or GOPATH mode.
GO111MODULE=on, the go command line will use modules without going to the GOPATH directory at all.
GO111MODULE=auto, the default value. The go command line will decide whether to enable the module function according to the current directory. This situation can be divided into two situations:
The current directory is outside GOPATH/src and contains the go.mod file
The current file is under the directory containing the go.mod file.
Initialization module
The test project directory structure is shown in the following figure:
After executing the go mod {package name} command in the root directory, a go.mod file will be generated, which will record the package and package version used by the project, which is a bit like the requirements.txt file in Python.
go.mod file
module hello go 1.17
Note: init is not required in subdirectories. All dependencies in subdirectories will be organized in the go.mod file in the root directory
Execute go run server.go to run the code, and you will find that go mod will automatically find dependencies and automatically download
go.mod file
module hello go 1.17 require ( github.com/golang/protobuf v1.5.2 // indirect github.com/goplus/gop v1.0.14 // indirect golang.org/x/net v0.0.0-20211123203042-d83791d6bcd9 // indirect golang.org/x/sys v0.0.0-20211124211545-fe61309f8881 // indirect golang.org/x/text v0.3.7 // indirect google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1 // indirect google.golang.org/grpc v1.42.0 // indirect google.golang.org/protobuf v1.27.1 // indirect )
We will carry out your orders
# Initialization module go mod init Module name # Our example go mod init hello # Running grpc server go run server.go
Reference project files
helloworld.proto
syntax = "proto3"; package hello; option go_package = "/protos"; // Define a service service Greeter { // Define a function rpc SayHello (HelloRequest) returns (HelloReply) {} } // Defines the input to the function message HelloRequest { string name = 1; } // Define the output of the function message HelloReply { string message = 1; }
Under the protos directory is the grpc protocol file generated by us. Understand proto . First, we need to edit a standard proto protocol file, and then execute the following compilation command to generate the go protocol file.
protoc -I=$SRC_DIR --go_out=$DST_DIR $SRC_DIR/helloworld.proto # Our example protoc.exe --go_out=plugins=grpc:. helloworld.proto
The generated helloworld.pb.go file is a file that both grpc client and grpc server need to reference. It is used to specify a standard communication rule. How to reference this file? We initialized the module name of our current project earlier, so we added "hello/protos" in import to reference the file.
grpc client example
client.go
package main import ( "log" "os" "golang.org/x/net/context" "google.golang.org/grpc" pb "hello/protos" ) const ( address = "localhost:8888" defaultName = "A less intelligent programmer" ) func main() { // Set up a connection to the server. conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn) // Contact the server and print out its response. name := defaultName if len(os.Args) > 1 { name = os.Args[1] } r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.Message) }
grpc server example
server.go
package main import ( "log" "net" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/reflection" pb "hello/protos" ) const ( port = ":8888" ) // GreeterServerImplementation is used to implement helloworld.GreeterServer. type GreeterServerImplementation struct{} // SayHello implements helloworld.GreeterServer func (s *GreeterServerImplementation) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello " + in.Name}, nil } func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGreeterServer(s, &GreeterServerImplementation{}) // Register reflection service on gRPC server. reflection.Register(s) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } }
Operation results
# Running grpc server go run server.go # Run grpc client go run client.go