Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

林子篆
林子篆

Posted on • Originally published atdannypsnl.github.io on

     

gRPC quick start in Go

What is RPC? RPC means “remote procedure call”. The concept is called a remote function as a local function.

Then gRPC? It is a framework that helps you create RPC.

Traditional RPC has some problem making it hard to use. For example, how do you know, what type of message you get?

Usually, we use JSON or others format. But marshal & unmarshal quickly became a big issue. Because as time goes on, we don’t actually know which service use which field, thus we can’t reduce anything.

And server & client will get further farther for the same reason.

These all, won’t be an issue in gRPC.

In gRPC, you define a*.proto file for your service.

At here, we will create one namedUserService

syntax="proto3";packageuser;serviceUserService{rpcGetUser(Empty)returns(User){}}// define message typemessageEmpty{}messageUser{stringname=1;int32age=2;}
Enter fullscreen modeExit fullscreen mode

To generate code, I usually usego generate ./...

So let’s have a filegen.go, just leave a comment about what command you want to execute.

//go:generate sh -c "protoc -I./user --go_out=plugins=grpc:./user ./user/*.proto"
Enter fullscreen modeExit fullscreen mode

Implement service:

import"path/to/grpc_generated/user"typeUserServicestruct{}func(us*UserService)GetUser(ctxcontext.Context,u*user.Empty)(*user.User,error){return&user.UserName{Name:"Danny",Age:21,},nil}
Enter fullscreen modeExit fullscreen mode

Create server:

import("net""path/to/grpc_generated/user""google.golang.org/grpc")funcmain(){l,err:=net.Listen("tcp",":50051")// handle errserver:=grpc.NewServer()service:=user.UserServiceServer(&UserService{})user.RegisterUserServiceServer(server,service)err=server.Serve(l)// handle err}
Enter fullscreen modeExit fullscreen mode

Final is our client:

import("fmt""net""path/to/grpc_generated/user""google.golang.org/grpc")funcmain(){conn,err:=grpc.Dial("localhost:50051",grpc.WithInsercure())// handle errdeferconn.Close()client:=user.NewUserServiceClient(conn)u,err:=client.GetUser(context.Background(),&user.Empty{})// handle errfmt.Printf("Name: %s, Age: %d",u.Name,u.Age)}
Enter fullscreen modeExit fullscreen mode

After that, rungo generate ./... from project root dir.

Thengo run server.go, open another terminal,go run client.go

I usually won’t commit generated code(unless commit it makes sense), so I usually will write*.pb.go in file.gitignore

More info:

Top comments(7)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
ernsheong profile image
Jonathan ES Lin
Cloud Geek at JonCloudGeek.com. Consultant and Tinkerer at BelianTech.com
  • Location
    Kuala Lumpur, Malaysia
  • Joined
• Edited on• Edited

What's interesting to me is that when I create the GRPC client in another package (outside main) and try to use it elsewhere... the GRPC calls fails with:

rpc error: code = Canceled desc = grpc: the client connection is closing

Any thoughts on this peculiarity?

CollapseExpand
 
dannypsnl profile image
林子篆
I am a programming language theory lover; good at system software like Networking, OS.
  • Email
  • Location
    Taiwan
  • Education
    Kaohsiung Medical University
  • Joined

Not sure what happened on your computer, could you provide a sample for reproducing?

CollapseExpand
 
ernsheong profile image
Jonathan ES Lin
Cloud Geek at JonCloudGeek.com. Consultant and Tinkerer at BelianTech.com
  • Location
    Kuala Lumpur, Malaysia
  • Joined

Thanks for the reply. I figured it out. Gotta be careful withdefer conn.Close() if calling outside main function... After function ends it will close the connection and the client cannot be used anymore.

Thread Thread
 
dannypsnl profile image
林子篆
I am a programming language theory lover; good at system software like Networking, OS.
  • Email
  • Location
    Taiwan
  • Education
    Kaohsiung Medical University
  • Joined

Good to hear that; yes, better to using context if you want to manage the lifecycle. It provides a not bad abstraction for stopping a goroutine.

CollapseExpand
 
bimbimprasetyoafif profile image
Bimo Prasetyo Afif
keep relax.work and learn...Playing Python and Golang(Backend).
  • Location
    Surabaya, Indonesia
  • Education
    EEPIS
  • Joined
• Edited on• Edited

Hey, i already have golang backend with rest api implemented. can i use grpc without make .proto file ? because i already have service, interface, repo, etc

CollapseExpand
 
dannypsnl profile image
林子篆
I am a programming language theory lover; good at system software like Networking, OS.
  • Email
  • Location
    Taiwan
  • Education
    Kaohsiung Medical University
  • Joined

A short answer is it's possible, but that also means you are using HTTP2 directly.
That would make the gRPC became useless. Or you have to implement client/server-side abstraction for RPC.
Therefore I guess you probably can use .proto, just redirect to existed services.

CollapseExpand
 
bimbimprasetyoafif profile image
Bimo Prasetyo Afif
keep relax.work and learn...Playing Python and Golang(Backend).
  • Location
    Surabaya, Indonesia
  • Education
    EEPIS
  • Joined

maybe last option helpful for me. okay i will try it. thanks for suggest me :)

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a programming language theory lover; good at system software like Networking, OS.
  • Location
    Taiwan
  • Education
    Kaohsiung Medical University
  • Joined

More from林子篆

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp