A simple LibraryService to demonstrate how to use Bazel+Go+gRPC
A simple library service (server and client).
Pre-work
The following instructions are tested on Ubuntu 16.04 (LTS).
-
Install Bazel
Bazel is our build tool. It is written in Java. Install Java and then Bazel.
$ sudo apt-get install bazel
Complete instructions for intalling Bazel on Ubuntu.
-
Install Git
Git is our version control system. It is used by Bazel to download some of our external dependencies (like Protocol Buffers, gRPC, and Bazel's Go rules.
$ sudo apt-get install git
-
(Optional) Install Go
Go is a programming language and is very good at writting large-scale distributed systems. Our service and client are written in Go.
$ sudo apt-get install golang-go
Compelte instructions for installing Go on Ubuntu
-
(Optional) Install Gazelle
Gazelle is a helper tool that automatically generates Bazel BUILD files for Go and makes your life easier.
$ go install github.com/bazelbuild/bazel-gazelle/cmd/gazelle@latest
-
(Optional) Install Buildifier
Bazel Buildtools are helpers tools for Bazel. Buildifier cleans up and formats Bazel build files.
$ go install github.com/bazelbuild/buildtools/buildifier@latest
Clone
$ git clone git@github.com:ghasemloo/libraryservice.git
$ cd libraryservice
Bazel
Build and Test
$ bazel build ...
$ bazel test ...
Run the server and the client
In one terminal run the server:
$ bazel run server/server -- --logtostderr
In another terminal run the client to send requests to the server:
$ bazel run client/client -- --logtostderr
Go (without Bazel)
Go Module
$ go mod init github.com/ghasemloo/libraryservice
$ go mod tidy
Proto Compiler for Go
Install Protobuf Compiler to generate Go packages for proto files:
$ sudo apt-get install protobuf-compiler
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
Generated Go Proto Packages
$ protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative ./proto/api/api.proto
$ protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative ./proto/storage/storage.proto
Build and Test
$ go build ./...
$ go test ./...
Run the server and the client
In two different terminals run:
$ go run ./server/main.go
$ go run ./client/main.go
Gazelle
Updating WORKSPACE.bazel
from go.mod
:
$ gazelle update-repos --proto_import_prefix="github.com/ghasemloo/libraryservice" --from_file=./go.mod --prune
Creating/updating BUILD.bazel
files:
$ gazelle fix -go_prefix github.com/ghasemloo/libraryservice
You can also use Bazel (gazelle
commands and paramters are configured in the BUILD.bazel
):
$ bazel run //:gazelle-update-repos
$ bazel run //:gazelle
References