<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Pantomath - Medium]]></title>
        <description><![CDATA[Pantomath is a cutting edge monitoring solution - Medium]]></description>
        <link>https://medium.com/pantomath?source=rss----cf62d19c744---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Pantomath - Medium</title>
            <link>https://medium.com/pantomath?source=rss----cf62d19c744---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:40:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/pantomath" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Veda of Testing]]></title>
            <link>https://medium.com/pantomath/the-five-mantras-of-testing-a528be3ca229?source=rss----cf62d19c744---4</link>
            <guid isPermaLink="false">https://medium.com/p/a528be3ca229</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Charles Francoise]]></dc:creator>
            <pubDate>Thu, 15 Mar 2018 14:01:02 GMT</pubDate>
            <atom:updated>2018-03-15T14:01:02.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Five Mantras of Testing</h3><p>I used not to do unit testing. I kept finding excuses. “My code doesn’t fit with testing.” “I can’t unit test, this needs a running database.” “I can’t test all cases and I don’t know what to test.” “There’s already so much untested code in the codebase, what’s the point in testing it now?”</p><p>What I finally understood is that I missed the TDD train back when I should have caught it, and I found it hard to learn as an autodidact.</p><p>What finally got me into it was <a href="https://golang.org/">Go</a>. Having the testing framework baked into the <a href="https://golang.org/pkg/testing/">stdlib</a> and the <a href="https://golang.org/cmd/go/#hdr-Test_packages">toolchain</a> really did it for me. I’ve been unit testing ever since, and reaping the many benefits. If you’ve been facing the same problems with the TDD learning curve, here are a few mantras I’ve been applying every day that changed my life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mPfnOqACUuoTJ1RV." /><figcaption>Photo by <a href="https://unsplash.com/@jedadan?utm_source=medium&amp;utm_medium=referral">Jed Adan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Test Is Your First Client</h3><p>How do you check a function or method you’ve written works? Do you run it, log the output, and make sure it matches your expectations? Do you use step-by-step debugging to watch what happens to your inputs? Stop doing this. If you have some known inputs and expected outputs to your function, don’t do this by hand: write the test that does this. <strong>Even if you only have one case. Code it, don’t just keep it in your head.</strong> It’ll be easier to add more cases to a pre-existing test, than to start writing them from scratch later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pVmBFVve4dkN0gN3." /><figcaption>Photo by <a href="https://unsplash.com/@florianklauer?utm_source=medium&amp;utm_medium=referral">Florian Klauer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>If you can’t test it, break it into pieces</h3><p>Unit testing taught me to break behavior into smaller, easier to understand pieces. Have you ever looked at a piece of code and thought: “I can’t test this, it does too many things”? That often means you can (and should) isolate independent tasks, separate them into “units” and compose them to get the expected behavior. <strong>Then test each of these units independently.</strong> You’ll find your code is much easier to reason with, understand, read, reuse, factorize… You’ll even find yourself getting better at thinking in terms of “mutability”, “const-ness”, “pure functions” since these concepts will have important repercussions on how and what you test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uPSKB0MF1PoYMOEr." /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>In Tests We Trust</h3><p>Exhaustive testing is impossible, but your end goal should be that your tests give you a good enough idea that your codebase works as a whole. In particular, passing your test suite should make you 90% sure that you can merge your code. This means that not only should you expect previous tests to break if you’ve introduced a bug, but that all code you write should be tested to give the next developer the same kind of assurance. It does not mean you should aim for an arbitrary metric like “99% coverage”, or be afraid to commit your code if the tests don’t cover every corner case. In practice, <strong>no form of testing or automation will avoid bugs</strong>, but it’s reasonable to assume that you can rely on tests to validate the behavior of your program, and work towards that goal. Speaking of bugs…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JrjH0I0Vz0oNO0JL." /><figcaption>Photo by <a href="https://unsplash.com/@dsiglin?utm_source=medium&amp;utm_medium=referral">David Siglin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>You Fix It, You Test It</h3><p>So you tested everything and something still broke in production? Don’t panic. It’s to be expected. But there’s something to learn, here: your tests weren’t covering the buggy case. Once you’ve fixed the bug, add a test case for that specific issue. It will make sure your fix prevents the bug from occurring in the future. It will also prevent the bug from reappearing later in another commit. <strong>This is called a <em>non-regression test</em>.</strong> Additionally, the test itself serves as a historical marker of the project, and contains information as to where and when you found a special case about your program. The insights gained from fixing a bug are easier to share and talk about when there’s an explicit piece of code that guards against it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8eirgGgWLRBlbeaR." /><figcaption>Photo by <a href="https://unsplash.com/@randallbruder?utm_source=medium&amp;utm_medium=referral">Randall Bruder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>F**k it, we’ll do it live</h3><p>Often, it will seem hard to test code that depends on some “live” parts, i.e. dependencies from outside of your code. A database, an HTTP API, a filesystem. All these pieces are independent from your codebase, while the code you want to test performs — respectively—SQL queries, HTTP requests, file I/O… You’ll hear a lot about mocking, dependency injection, setup and teardown. These are all important things in the world of testing. But sometimes setting up a mockup of your database is more work than writing the code and the tests combined. <strong>Don’t be ashamed to actually test against a live instance of the database full of test values.</strong> Just make sure the test setup is well-documented and easily reproducible for other developers. Some will argue this is borderline “integration testing” and they’ll be right. Is the distinction that important? As long as you have a surefire, reproducible way to test your behavior, you’re one step closer to shipping your code. And good code at that. Remember: <strong>you aren’t shipping your tests.</strong></p><p>These are a few of the guidelines I apply when writing tests. I used to dread testing because I didn’t know where a “unit” began and ended. I used to start writing tests and get “<a href="https://en.wikipedia.org/wiki/Analysis_paralysis">analysis paralysis</a>” trying to cover every possible input and precondition. Following these few rules, I now feel confident delivering robust code, and I even have fun writing tests!</p><p>How did you start testing your code? Learn it in school? Had a mentor? What are your techniques to write better unit tests? Comment below and let me know.</p><p><em>If you liked this article, click the 👏 below, share and repost.</em></p><p><em>I am currently working on Panto. Panto is a modern, open-source monitoring solution, built for performance, that bridges the gaps across all levels of your company. The well-being of your infrastructure is everyone’s business. </em><a href="http://goo.gl/tcxtXq"><em>Keep up with the project</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a528be3ca229" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pantomath/the-five-mantras-of-testing-a528be3ca229">The Veda of Testing</a> was originally published in <a href="https://medium.com/pantomath">Pantomath</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with forks in Go]]></title>
            <link>https://medium.com/pantomath/working-with-forks-in-go-25451aee0dbc?source=rss----cf62d19c744---4</link>
            <guid isPermaLink="false">https://medium.com/p/25451aee0dbc</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[fork]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Charles Francoise]]></dc:creator>
            <pubDate>Mon, 15 Jan 2018 15:43:48 GMT</pubDate>
            <atom:updated>2018-01-15T22:04:12.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eX0kzyaeP9IS5YCCA2wIg.png" /><figcaption>Photo by Ursula Spaulding on <a href="https://unsplash.com/photos/bmxYEhqLVEk">Unsplash</a></figcaption></figure><h4>How to work on a forked repository of an open-source Go package</h4><p>Have you ever wanted to create a fork of a Go package you’re using? Maybe you need to add a feature, specific to your use case, and there is no other way than to change it inside the code. Or maybe you want to fix a bug and submit a PR to an open-source project.</p><p>Whatever the case, Go, with its location-based import system, makes it hard to swap implementations of a package. If you try to just swap it into place, you’ll most likely get an error along the lines of: cannot use s (type &quot;fork&quot;.SomeStruct) as type &quot;original&quot;.SomeStruct in argument to SomeFunc as soon as you pass your data types to a function defined in another file.</p><p>You can fix this with heavy refactoring — changing imports in your own code, and typecasting everything coming in from or going out to another package — but it’s near impossible on a large project with many files.</p><p><a href="https://github.com/golang/proposal/blob/master/design/18130-type-alias.md">Type aliases</a> can help, but with a little bit of Git magic, you can seamlessly swap a package for your fork and keep hacking away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*ZdrSHxADhD159gY3.jpg" /></figure><h3>Fork and fix</h3><p>I won’t go into detail on how to create a fork and submit a PR, GitHub has <a href="https://guides.github.com/activities/forking/">extensive</a> <a href="https://help.github.com/articles/fork-a-repo/">documentation</a> <a href="https://help.github.com/articles/creating-a-pull-request-from-a-fork/">on the subject</a>. I’ll just assume you’ve clicked the “Fork” button on GitHub, and now have your own repository containing a duplicate of the original source.</p><p>But as we’ve said, you can’t just go get the forked repository, since all the import paths will be wrong. What we want is to have your local branch, inside your GOPATH, track your forked remote repository, instead of the original.</p><p>Let’s start by adding a remote. From the package source path, type the following:</p><pre>$ git remote add forked &lt;remote repository url&gt;</pre><p>Then, let’s make sure the local branch tracks the forked remote, and not the origin anymore.</p><pre>$ git branch -u forked/master<br>Branch master set up to track remote branch master from forked.</pre><p>After this line, you can start committing and pushing to your own fork, and all Go packages relying the package will transparently use your own fork of the code.</p><p>This is useful, for example, if you’re sure of a bugfix, as you can start working with the fixed version of the code without waiting for the changes to be merged upstream.</p><p>When you want to revert to tracking the origin, perhaps because your PR has been merged and you have deleted your fork, or because you need to use the original code for some other project, just type:</p><pre>$ git branch -u origin/master<br>Branch master set up to track remote branch master from origin.</pre><pre># Reset local branch to remote HEAD<br>$ git reset — hard origin/master</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xZMbu5oCiXDCH3vk.jpg" /></figure><p>With these few lines of git, I can quickly fork and work on an open-source Go package. It’s made my collaboration on open-source projects that much easier. What is your workflow for collaborating on open-source Go projects? Do you see any mistakes or caveats? Feel free to comment!</p><p><em>We are currently working on Pantomath. Pantomath is a modern, open-source monitoring solution, built for performance, that bridges the gaps across all levels of your company. The well-being of your infrastructure is everyone’s business. </em><a href="http://goo.gl/tcxtXq"><em>Keep up with the project</em></a></p><p><em>Article originally posted on </em><a href="https://dev.to/loderunner/working-with-forks-in-go-3ab6"><em>ThePracticalDev</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25451aee0dbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pantomath/working-with-forks-in-go-25451aee0dbc">Working with forks in Go</a> was originally published in <a href="https://medium.com/pantomath">Pantomath</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go tools & GitLab — how to do Continuous Integration like a boss]]></title>
            <link>https://medium.com/pantomath/go-tools-gitlab-how-to-do-continuous-integration-like-a-boss-941a3a9ad0b6?source=rss----cf62d19c744---4</link>
            <guid isPermaLink="false">https://medium.com/p/941a3a9ad0b6</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Julien Andrieux]]></dc:creator>
            <pubDate>Mon, 06 Nov 2017 12:54:14 GMT</pubDate>
            <atom:updated>2017-11-12T15:36:39.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3A-s2eExektSb4S48r0FQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/IClZBVw5W5A?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Todd Quackenbush</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>At <a href="https://pantomath.io/">Pantomath</a>, we use <a href="https://about.gitlab.com/">GitLab</a> for all our development work. The purpose of this paper is not to present GitLab and all <a href="https://about.gitlab.com/features/">its features</a>, but to introduce how we use these tools to ease our lives.</p><p>So what is it all about? To automate everything that is related to your development project, and let you focus on your code. We’ll cover the <a href="https://en.wikipedia.org/wiki/Lint_(software)">lint</a>, <a href="https://en.wikipedia.org/wiki/Unit_testing">unit tests</a>, <a href="https://en.wikipedia.org/wiki/Race_condition">data race</a>, <a href="https://clang.llvm.org/docs/MemorySanitizer.html">memory sanitizer</a>, <a href="https://en.wikipedia.org/wiki/Code_coverage">code coverage</a>, and build.</p><p>All the code shown in this post is available at <a href="https://gitlab.com/pantomath-io/demo-tools">https://gitlab.com/pantomath-io/demo-tools</a>. So feel free to get the repository, and use the tags to navigate in it. The repository should be placed in the src folder of your $GOPATH:</p><pre>$ go get -v -d gitlab.com/pantomath-io/demo-tools<br>$ cd $GOPATH/src/gitlab.com/pantomath-io/demo-tools</pre><h3>Go tools</h3><p>Luckily, Go comes with a <a href="https://golang.org/cmd/go/">lot of useful tools</a>, to build, test and check your code. In fact, it’s all there. We’ll just add extra tools to glue them together. But before we go there, we need to take them one by one, and see what they do.</p><h4>Package list</h4><p>Your go project is a collection of packages, as described in the <a href="https://golang.org/doc/code.html">official doc</a>. Most of the following tools will be fed with these packages, and thus the first command we need is a way to list the packages. Hopefully, go covers our back with the list subcommand (<a href="https://golang.org/cmd/go/#hdr-List_packages">read the fine manual</a> and this <a href="https://dave.cheney.net/2014/09/14/go-list-your-swiss-army-knife">excellent post from Dave Cheney</a>):</p><pre>$ go list ./...</pre><p>Note that we want to avoid applying our tools on external resources, and restrict it to <strong>our</strong> code. So we need to get rid of the <a href="https://golang.org/cmd/go/#hdr-Vendor_Directories">vendor directories</a>:</p><pre>$ go list ./... | grep -v /vendor/</pre><h4>Lint</h4><p>This is the very first tool we use on the code: the linter. Its role is to make sure that the code respects the code style. This may sounds like an optional tool, or at least a “nice-to-have” but it really helps to keep consistent style over your project.</p><p>This linter is not part of go <em>per se</em>, so you need to grab it and install it by hand (see <a href="https://github.com/golang/lint">official doc</a>).</p><p>The usage is fairly simple: you just run it on the packages of your code (you can also point the .go files):</p><pre>$ golint -set_exit_status $(go list ./... | grep -v /vendor/)</pre><p>Note the -set_exit_status option. By default, golint only prints the style issues, and returns (with a 0 return code), so the CI never considers something went wrong. If you specify the -set_exit_status, the return code from golint will be different from 0 if any style issue is encountered.</p><h4>Unit test</h4><p>These are the most common tests you can run on your code. For each .go file, we need to have an associated _test.go file holding the unit tests. You can run the tests for all the packages with the following command:</p><pre>$ go test -short $(go list ./... | grep -v /vendor/)</pre><h4>Data race</h4><p>This is usually a hard subject to cover, but the go tool has it by default (but only available on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64). For more information about data race, see <a href="https://golang.org/doc/articles/race_detector.html">this article</a>. Meanwhile, here is how to run it:</p><pre>$ go test -race -short $(go list ./... | grep -v /vendor/)</pre><h4>Memory sanitizer</h4><p>Clang has a nice detector for uninitialized reads called <a href="https://clang.llvm.org/docs/MemorySanitizer.html">MemorySanitizer</a>. The go test tool is kind enough to interact with this Clang module (as soon as you are on linux/amd64 host and using a recent version of Clang/LLVM (&gt;=3.8.0). This command is how to run it:</p><pre>$ go test -msan -short $(go list ./... | grep -v /vendor/)</pre><h4>Code coverage</h4><p>This is also a must have to evaluate the health of your code, and see what the part of code is under unit tests and what part is not. <a href="https://twitter.com/rob_pike">Rob Pike</a> wrote a <a href="https://blog.golang.org/cover">full post on that very subject</a>.</p><p>To calculate the code coverage ratio, we need to run the following script:</p><pre>$ PKG_LIST=$(go list ./... | grep -v /vendor/)<br>$ for package in ${PKG_LIST}; do<br>    go test -covermode=count -coverprofile &quot;cover/${package##*/}.cov&quot; &quot;$package&quot; ;<br>done<br>$ tail -q -n +2 cover/*.cov &gt;&gt; cover/coverage.cov<br>$ go tool cover -func=cover/coverage.cov</pre><p>If we want to get the coverage report in HTML format, we need to add the following command:</p><pre>$ go tool cover -html=cover/coverage.cov -o coverage.html</pre><h4>Build</h4><p>Last but not least, once the code has been fully tested, we might want to compile it to make sur we can build a working binary.</p><pre>$ go build -i -v gitlab.com/pantomath-io/demo-tools</pre><h3>Makefile</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-tools/tags/init-makefile"><em>init-makefile</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ip_q_6I-kNpUjuPMOutuTA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/qJE5Svhs2ek?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matt Artz</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Now we have all the tools that we may use in the context of Continuous Integration, we can wrap them all in a <a href="https://gitlab.com/pantomath-io/demo-tools/blob/init-makefile/Makefile">Makefile</a>, and have a consistent way to call them.</p><p>The purpose of this doc is not to present make, but you can refer to <a href="https://www.gnu.org/software/make/manual/make.html">official documentation</a> to learn more about it.</p><pre>PROJECT_NAME := &quot;demo-tools&quot;<br>PKG := &quot;gitlab.com/pantomath-io/$(PROJECT_NAME)&quot;<br>PKG_LIST := $(shell go list ${PKG}/... | grep -v /vendor/)<br>GO_FILES := $(shell find . -name &#39;*.go&#39; | grep -v /vendor/ | grep -v _test.go)</pre><pre>.PHONY: all dep build clean test coverage coverhtml lint</pre><pre>all: build</pre><pre>lint: ## Lint the files<br> @golint -set_exit_status ${PKG_LIST}</pre><pre>test: ## Run unittests<br> @go test -short ${PKG_LIST}</pre><pre>race: dep ## Run data race detector<br> @go test -race -short ${PKG_LIST}</pre><pre>msan: dep ## Run memory sanitizer<br> @go test -msan -short ${PKG_LIST}</pre><pre>coverage: ## Generate global code coverage report<br> ./tools/coverage.sh;</pre><pre>coverhtml: ## Generate global code coverage report in HTML<br> ./tools/coverage.sh html;</pre><pre>dep: ## Get the dependencies<br> @go get -v -d ./...</pre><pre>build: dep ## Build the binary file<br> @go build -i -v $(PKG)</pre><pre>clean: ## Remove previous build<br> @rm -f $(PROJECT_NAME)</pre><pre>help: ## Display this help screen<br> @grep -h -E &#39;^[a-zA-Z_-]+:.*?## .*$$&#39; $(MAKEFILE_LIST) | awk &#39;BEGIN {FS = &quot;:.*?## &quot;}; {printf &quot;\033[36m%-30s\033[0m %s\n&quot;, $$1, $$2}&#39;</pre><p>What do we have, now? One target for any tool previously presented, and 3 more targets for:</p><ul><li>installation of dependencies (dep);</li><li>housekeeping of the project (clean);</li><li>some nice and shiny help (help).</li></ul><p>Note that we also had to create a script for the code coverage work. This is because implementing loops over files in a Makefile is a pain. So the work is done in a bash script, and the Makefile only triggers this script.</p><p>You can try the Makefile with the following commands:</p><pre>$ make help<br>$ make lint<br>$ make coverage</pre><h3>Continuous Integration</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-tools/tags/init-ci"><em>init-ci</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQ87XIRgONJ9dOKw8CxPAA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/Gt1A0jNzzbM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Max Panamá</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Now the tools are in place, and we can run various tests on our code, we’d like to automate these, on your repository. Luckily, GitLab offers <a href="https://about.gitlab.com/features/gitlab-ci-cd/">CI pipelines</a> just for this. And the setup for this is pretty straightforward: all you create is a .gitlab-ci.yml file at the root of the repository.</p><p>The <a href="https://docs.gitlab.com/ee/ci/yaml/">full documentation</a> on this Yaml file presents all the options, but you can start with this <a href="https://gitlab.com/pantomath-io/demo-tools/blob/init-ci/.gitlab-ci.yml">.gitlab-ci.yml</a>:</p><pre>image: golang:1.9</pre><pre>cache:<br>  paths:<br>    - /apt-cache<br>    - /go/src/github.com<br>    - /go/src/golang.org<br>    - /go/src/google.golang.org<br>    - /go/src/gopkg.in</pre><pre>stages:<br>  - test<br>  - build</pre><pre>before_script:<br>  - mkdir -p /go/src/gitlab.com/pantomath-io /go/src/_/builds<br>  - cp -r $CI_PROJECT_DIR /go/src/gitlab.com/pantomath-io/pantomath<br>  - ln -s /go/src/gitlab.com/pantomath-io /go/src/_/builds/pantomath-io<br>  - make dep</pre><pre>unit_tests:<br>  stage: test<br>  script:<br>    - make test</pre><pre>race_detector:<br>  stage: test<br>  script:<br>    - make race</pre><pre>memory_sanitizer:<br>  stage: test<br>  script:<br>    - make msan</pre><pre>code_coverage:<br>  stage: test<br>  script:<br>    - make coverage</pre><pre>code_coverage_report:<br>  stage: test<br>  script:<br>    - make coverhtml<br>  only:<br>  - master</pre><pre>lint_code:<br>  stage: test<br>  script:<br>    - make lint</pre><pre>build:<br>  stage: build<br>  script:<br>    - make</pre><p>If you break down the file, here are some explanations on its content:</p><ul><li>The first thing is to choose what Docker image will be used to run the CI. Head to the <a href="https://hub.docker.com/">Docker Hub</a> to choose the right image for your project.</li><li>Then, you specify some folders of this image <a href="https://docs.gitlab.com/ee/ci/yaml/#cache">to be cached</a>. The goal here is to avoid downloading the same content several times. Once a job is completed, the listed paths will be archived, and next job will use the same archive.</li><li>You define the different stages that will group your jobs. In our case, we have two <a href="https://docs.gitlab.com/ee/ci/yaml/#stages">stages</a> (to be processed in that order): test and build. We could have other stages, such as deploy.</li><li>The before_script <a href="https://docs.gitlab.com/ee/ci/yaml/#before_script">section</a> defines the commands to run in the Docker container right before the job is actually done. In our context, the commands just copy or link the repository deployed in the $GOPATH, and install dependencies.</li><li>Then come the actual <a href="https://docs.gitlab.com/ee/ci/yaml/#jobs">jobs</a>, using the Makefile targets. Note the special case for code_coverage_report where execution is restricted to the master branch (we don’t want to update the code coverage report from feature branches for instance).</li></ul><p>As we commit/push the .gitlab-ci.yml file in the repository, the CI is <a href="https://gitlab.com/pantomath-io/demo-tools/pipelines/13481935">automatically triggered</a>. And the pipeline fails. How come?</p><p>The <a href="https://gitlab.com/pantomath-io/demo-tools/-/jobs/38690212">lint_code job</a> fails because it can’t find the golint binary:</p><pre>$ make lint<br>make: golint: Command not found<br>Makefile:11: recipe for target &#39;lint&#39; failed<br>make: *** [lint] Error 127</pre><p>So, <a href="https://gitlab.com/pantomath-io/demo-tools/commit/17a0206eb626504e559f56773e2d81c7b5808dbe">update</a> your Makefile to install golint as part of the dep target.</p><p>The <a href="https://gitlab.com/pantomath-io/demo-tools/-/jobs/38690209">memory_sanitizer job</a> fails because gcc complains:</p><pre>$ make msan<br># runtime/cgo<br>gcc: error: unrecognized argument to -fsanitize= option: &#39;memory&#39;<br>Makefile:20: recipe for target &#39;msan&#39; failed<br>make: *** [msan] Error 2</pre><p>But remember we need to use Clang/LLVM &gt;=3.8.0 to enjoy the -msan option in go test command.</p><p>We have 2 options here:</p><ul><li>either we setup Clang in the job (using before_script);</li><li>or we use a Docker image with Clang installed by default.</li></ul><p>The first option is nice, but that implies to have this setup done <strong>for every single job</strong>. This is going to be so long, we should do it once and for all. So we prefer the second option, which is a good way to play with <a href="https://docs.gitlab.com/ce/user/project/container_registry.html">GitLab Registry</a>.</p><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-tools/tags/use-own-docker"><em>use-own-docker</em></a></p><p>We need to create a <a href="https://gitlab.com/pantomath-io/demo-tools/blob/use-own-docker/Dockerfile">Dockerfile</a> for the container (as usual: read the <a href="https://docs.docker.com/engine/reference/builder">official documentation</a> for more options about it):</p><pre># Base image: <a href="https://hub.docker.com/_/golang/">https://hub.docker.com/_/golang/</a><br>FROM golang:1.9<br>MAINTAINER Julien Andrieux &lt;<a href="/service/mailto:julien@pantomath.io">julien@pantomath.io</a>&gt;</pre><pre># Install golint<br>ENV GOPATH /go<br>ENV PATH ${GOPATH}/bin:$PATH<br>RUN go get -u github.com/golang/lint/golint</pre><pre># Add apt key for LLVM repository<br>RUN wget -O - <a href="https://apt.llvm.org/llvm-snapshot.gpg.key">https://apt.llvm.org/llvm-snapshot.gpg.key</a> | apt-key add -</pre><pre># Add LLVM apt repository<br>RUN echo &quot;deb <a href="http://apt.llvm.org/stretch/">http://apt.llvm.org/stretch/</a> llvm-toolchain-stretch-5.0 main&quot; | tee -a /etc/apt/sources.list</pre><pre># Install clang from LLVM repository<br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends \<br>    clang-5.0 \<br>    &amp;&amp; apt-get clean \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*</pre><pre># Set Clang as default CC<br>ENV set_clang /etc/profile.d/set-clang-cc.sh<br>RUN echo &quot;export CC=clang-5.0&quot; | tee -a ${set_clang} &amp;&amp; chmod a+x ${set_clang}</pre><p>The container built out of this Dockerfile will be based on <a href="https://hub.docker.com/_/golang/">golang:1.9</a> image (the one referenced in the <a href="https://gitlab.com/pantomath-io/demo-tools/blob/init-ci/.gitlab-ci.yml">.gitlab-ci.yml</a> file).</p><p>While we’re at it, we install golint in the container, so we have it available. Then we follow <a href="http://apt.llvm.org/">official way</a> of installing Clang 5.0 from LLVM repository.</p><p>Now we have the Dockerfile in place, we need to build the container image and make it available for GitLab:</p><pre>$ docker login registry.gitlab.com<br>$ docker build -t registry.gitlab.com/pantomath-io/demo-tools .<br>$ docker push registry.gitlab.com/pantomath-io/demo-tools</pre><p>The first command connects you to the GitLab Registry. Then you build the container image described in the Dockerfile. And finally, you push it to the GitLab Registry.</p><p>Take a look at the <a href="https://gitlab.com/pantomath-io/demo-tools/container_registry">Registry for your repository</a>, you’ll see your image, ready to be used. And to have the CI using your image, you just need to update the <a href="https://gitlab.com/pantomath-io/demo-tools/blob/use-own-docker/.gitlab-ci.yml">.gitlab-ci.yml</a> file:</p><pre>image: golang:1.9</pre><p>becomes</p><pre>image: registry.gitlab.com/pantomath-io/demo-tools:latest</pre><p>One last detail: you need to tell the CI to use the proper compiler (i.e. the CC environment variable), so we add the variable initialization in the <a href="https://gitlab.com/pantomath-io/demo-tools/blob/use-own-docker/.gitlab-ci.yml">.gitlab-ci.yml</a> file:</p><pre>export CC=clang-5.0</pre><p>Once the modification are done, next commit will trigger the pipeline, which now works:</p><p><a href="https://gitlab.com/pantomath-io/demo-tools/pipelines/13497136">https://gitlab.com/pantomath-io/demo-tools/pipelines/13497136</a></p><h3>Badges</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-tools/tags/init-badges"><em>init-badges</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pY_6oCiHZ_eLh0vfg5rDA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ZBadHaTUkP0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jakob Owens</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Now the tools are in place, every commit will launch a test suite, and you probably want to show it, and that’s legitimate :) The best way to do so is to use badges, and the best place for it is the <a href="https://gitlab.com/pantomath-io/demo-tools/blob/init-badges/README.md">README file</a>.</p><p>Edit it and add the 4 following badges:</p><ul><li>Build Status: the status of the last pipeline on the master branch:</li></ul><pre>[![Build Status](<a href="https://gitlab.com/pantomath-io/demo-tools/badges/master/build.svg)](https://gitlab.com/pantomath-io/demo-tools/commits/master)">https://gitlab.com/pantomath-io/demo-tools/badges/master/build.svg)](https://gitlab.com/pantomath-io/demo-tools/commits/master)</a></pre><ul><li>Coverage Report: the percentage of code covered by tests</li></ul><pre>[![Coverage Report](<a href="https://gitlab.com/pantomath-io/demo-tools/badges/master/coverage.svg)](https://gitlab.com/pantomath-io/demo-tools/commits/master)">https://gitlab.com/pantomath-io/demo-tools/badges/master/coverage.svg)](https://gitlab.com/pantomath-io/demo-tools/commits/master)</a></pre><ul><li>Go Report Card:</li></ul><pre>[![Go Report Card](<a href="https://goreportcard.com/badge/gitlab.com/pantomath-io/demo-tools)](https://goreportcard.com/report/gitlab.com/pantomath-io/demo-tools)">https://goreportcard.com/badge/gitlab.com/pantomath-io/demo-tools)](https://goreportcard.com/report/gitlab.com/pantomath-io/demo-tools)</a></pre><ul><li>License:</li></ul><pre>[![License MIT](<a href="https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://img.shields.io/badge/License-MIT-brightgreen.svg)">https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://img.shields.io/badge/License-MIT-brightgreen.svg)</a></pre><p>The coverage report needs a special configuration. You need to tell GitLab how to get that information, considering that there is a job in the CI that <em>displays</em> it when it runs.<br>There is a <a href="https://gitlab.com/help/user/project/pipelines/settings#test-coverage-parsing">configuration</a> to provide GitLab with a regexp, used in any job’ output. If the regexp matches, GitLab consider the match to be the code coverage result.</p><p>So head to Settings &gt; CI/CD in your repository, scroll down to the Test coverage parsing setting in the General pipelines settings section, and use the following regexp:</p><pre>total:\s+\(statements\)\s+(\d+.\d+\%)</pre><p>You’re all set! Head to the <a href="https://gitlab.com/pantomath-io/demo-tools/tree/init-badges">overview of your repository</a>, and look at your README:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*yGatxRvKorCAyR7_f6r87A.png" /></figure><h3>Conclusion</h3><p>What’s next? Probably more tests in you CI. You can also look at the CD (<a href="https://docs.gitlab.com/ee/ci/environments.html">Continuous Deployment</a>) to automate the deployment of your builds. The documentation can be done using <a href="https://godoc.org/-/about">GoDoc</a>. Note that you generate a coverage report with the code_coverage_report, but don’t use it in the CI. You can make the job copy the HTML file to a web server, using scp (see this <a href="https://docs.gitlab.com/ee/ci/ssh_keys/README.html">documentation</a> on how to use SSH keys).</p><p><em>Many thanks to </em><a href="https://medium.com/u/177d8b64f64f"><em>Charles Francoise</em></a><em> who co-wrote this paper and </em><a href="https://gitlab.com/pantomath-io/demo-tools"><em>https://gitlab.com/pantomath-io/demo-tools</em></a><em>.</em></p><p><em>We are currently working on Pantomath. Pantomath is a modern, open-source monitoring solution, built for performance, that bridges the gaps across all levels of your company. The well-being of your infrastructure is everyone’s business. </em><a href="http://goo.gl/tcxtXq"><em>Keep up with the project</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=941a3a9ad0b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pantomath/go-tools-gitlab-how-to-do-continuous-integration-like-a-boss-941a3a9ad0b6">Go tools &amp; GitLab — how to do Continuous Integration like a boss</a> was originally published in <a href="https://medium.com/pantomath">Pantomath</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we use gRPC to build a client/server system in Go]]></title>
            <link>https://medium.com/pantomath/how-we-use-grpc-to-build-a-client-server-system-in-go-dd20045fa1c2?source=rss----cf62d19c744---4</link>
            <guid isPermaLink="false">https://medium.com/p/dd20045fa1c2</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[protobuf]]></category>
            <dc:creator><![CDATA[Julien Andrieux]]></dc:creator>
            <pubDate>Mon, 09 Oct 2017 16:01:02 GMT</pubDate>
            <atom:updated>2018-01-08T08:59:53.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIjD685SfIfFV-xXtdIofg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/6uWHZ74S5Rk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Igor Ovsyannykov</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This post is a technical presentation on how we use <a href="https://grpc.io/">gRPC</a> (and <a href="https://developers.google.com/protocol-buffers/">Protobuf</a>) to build a robust client/server system.</p><p>I won’t go into the details of why we chose gRPC as the main communication protocol between our client and server, a lot of great posts already cover the subject (like <a href="https://grpc.io/blog/vendastagrpc">this one</a>, <a href="https://stackoverflow.com/questions/43682366/how-is-grpc-different-from-rest">this one</a> or <a href="https://thenewstack.io/grpc-lean-mean-communication-protocol-microservices/">this one</a>). But just to get the big picture: we are building a client-server system, using <a href="https://golang.org/">Go</a>, that needs to be fast, reliable, and that scales (thus we chose gRPC). We wanted the communication between the client and the server to be as small as possible, as secure as possible and fully compliant with both ends (thus we chose <a href="https://developers.google.com/protocol-buffers/">Protobuf</a>).</p><p>We also wanted to expose another interface on the server side, just in case we add a client that has no compatible gRPC implementation: a traditional REST interface. And we wanted that at (almost) no cost.</p><h3>Context</h3><p>We will start building a very simple client/server system, in Go, that will just exchange dummy messages. Once both communicate and understand each other, we’ll add extra features, such as TLS support, authentication, and a REST API.</p><p>The rest of this articles assumes you understand basic Go programming. It also assumes that you have protobuf package installed, and the protoccommand available (once again, many posts cover that topic, and there’s the <a href="https://developers.google.com/protocol-buffers/docs/proto3">official documentation</a>).<br>You will also need to install Go dependencies, such as the <a href="http://github.com/golang/protobuf">go implementation for protobuf</a>, and <a href="https://github.com/grpc-ecosystem/grpc-gateway">grpc-gateway</a>.</p><p>All the code shown in this post is available at <a href="https://gitlab.com/pantomath-io/demo-grpc">https://gitlab.com/pantomath-io/demo-grpc</a>. So feel free to get the repository, and use the tags to navigate in it. The repository should be placed in the src folder of your $GOPATH:</p><pre>$ go get -v -d gitlab.com/pantomath-io/demo-grpc<br>$ cd $GOPATH/src/gitlab.com/pantomath-io/demo-grpc</pre><h3>Defining the protocol</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-grpc/tree/init-protobuf-definiton"><em>init-protobuf-definition</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8g6AM5x4n64RCXYUjwtYQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/yri82tuk2TQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mark Rasmuson</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>First of all, you need to define the protocol, i.e. to define what can be said between client and server, and how. This is where Protobuf comes into play. It allows you to define two things: Services and Messages. A service is a collection of actions the server can perform at the client’s request, a message is the content of this request. To simplify, you can say that service defines <strong>actions,</strong> while message defines <strong>objects</strong>.</p><p>Write the following in <a href="https://gitlab.com/pantomath-io/demo-grpc/blob/init-protobuf-definition/api/api.proto">api/api.proto</a>:</p><pre>syntax = &quot;proto3&quot;;<br>package api;</pre><pre>message PingMessage {<br>  string greeting = 1;<br>}</pre><pre>service Ping {<br>  rpc SayHello(PingMessage) returns (PingMessage) {}<br>}</pre><p>So, you defined 2 things: a service called Ping that exposes a function called SayHello with an incoming PingMessage and returns a PingMessage ; and a message called PingMessage that consists in a single field called greeting which is a string.<br>You also specified that you are using the proto3 syntax, as opposed to proto2 (see <a href="https://developers.google.com/protocol-buffers/docs/proto3">documentation</a>).</p><p>This file is not usable like this: it needs to get compiled. Compiling the proto file means generating code for your chosen language, that your application will actually call.<br>In a shell, cd to the root directory of your project, and run the following command:</p><pre>$ protoc -I api/ \<br>    -I${GOPATH}/src \<br>    --go_out=plugins=grpc:api \<br>    api/api.proto</pre><p>This command generates the file api/api.pb.go, a Go source file that implements the gRPC code your application will use. You can look at it, but you shouldn’t change it (as it will be overwritten every time you run protoc).</p><p>You also need to define the function called by the service Ping, so create a file named api/handler.go:</p><pre>package api</pre><pre>import (<br>  &quot;log&quot;</pre><pre>  &quot;golang.org/x/net/context&quot;<br>)</pre><pre>// Server represents the gRPC server<br>type Server struct {<br>}</pre><pre>// SayHello generates response to a Ping request<br>func (s *Server) SayHello(ctx context.Context, in *PingMessage) (*PingMessage, error) {<br>  log.Printf(&quot;Receive message %s&quot;, in.Greeting)<br>  return &amp;PingMessage{Greeting: &quot;bar&quot;}, nil<br>}</pre><ul><li>the Server struct is just an abstraction of the server. It allows to “attach” some resources to your server, making them available during the RPC calls;</li><li>the SayHello function is the one defined in the Protobuf file, as the rpc call for the Ping service. If you don’t define it, you won’t be able to create the gRPC server;</li><li>SayHello takes a PingMessage as parameter, and returns a PingMessage. The PingMessage struct is defined in the api.pb.go file auto-generated from the api.proto definition. The function also has a Context parameter (see further presentation in the official <a href="https://blog.golang.org/context">blog post</a>). You’ll see later what use you can do of the Context. On the other side, it also returns an error, in case something bad happens.</li></ul><h3>Creating the simplest server</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-grpc/tags/init-server"><em>init-server</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gy5Z3hBbB3r1GUkB75D_eg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/3CS0Ne4wBPw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nathan Dumlao</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Now you have a protocol in place, you can create a simple server that implements the service and understands the message. Take your favorite editor and create the file <a href="https://gitlab.com/pantomath-io/demo-grpc/blob/init-server/server/main.go">server/main.go</a>:</p><pre>package main</pre><pre>import (<br>  &quot;fmt&quot;<br>  &quot;log&quot;<br>  &quot;net&quot;</pre><pre>  &quot;gitlab.com/pantomath-io/demo-grpc/api&quot;<br>  &quot;google.golang.org/grpc&quot;<br>)</pre><pre>// main start a gRPC server and waits for connection<br>func main() {<br>  // create a listener on TCP port 7777<br>  lis, err := net.Listen(&quot;tcp&quot;, fmt.Sprintf(&quot;:%d&quot;, 7777))<br>  if err != nil {<br>    log.Fatalf(&quot;failed to listen: %v&quot;, err)<br>  }</pre><pre>  // create a server instance<br>  s := api.Server{}</pre><pre>  // create a gRPC server object<br>  grpcServer := grpc.NewServer()</pre><pre>  // attach the Ping service to the server<br>  api.RegisterPingServer(grpcServer, &amp;s)</pre><pre>  // start the server<br>  if err := grpcServer.Serve(lis); err != nil {<br>    log.Fatalf(&quot;failed to serve: %s&quot;, err)<br>  }<br>}</pre><p>Let me break down to code to make it clearer:</p><ul><li>note that you import the api package, so that the Protobuf service handlers and theServer struct are available;</li><li>the main function starts by creating a TCP listener on the port you want to bind your gRPC server to;</li><li>then the rest is pretty straight forward: you create an instance of your Server, create an instance of a gRPC server, register the service, and start the gRPC server.</li></ul><p>You can compile your code to get a server binary:</p><pre>$ go build -i -v -o bin/server gitlab.com/pantomath-io/demo-grpc/server</pre><h3>Creating the simplest client</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-grpc/tree/init-client"><em>init-client</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6G6qANKUoyZn3awfRii1g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/RLJnH4Mt9A0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clem Onojeghuo</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The client also imports the api package, so that the message and the service are available. So create the file client/main.go:</p><pre>package main</pre><pre>import (<br>  &quot;log&quot;</pre><pre>  &quot;gitlab.com/pantomath-io/demo-grpc/api&quot;<br>  &quot;golang.org/x/net/context&quot;<br>  &quot;google.golang.org/grpc&quot;<br>)</pre><pre>func main() {<br>  var conn *grpc.ClientConn</pre><pre>  conn, err := grpc.Dial(&quot;:7777&quot;, grpc.WithInsecure())<br>  if err != nil {<br>    log.Fatalf(&quot;did not connect: %s&quot;, err)<br>  }<br>  defer conn.Close()</pre><pre>  c := api.NewPingClient(conn)</pre><pre>  response, err := c.SayHello(context.Background(), &amp;api.PingMessage{Greeting: &quot;foo&quot;})<br>  if err != nil {<br>    log.Fatalf(&quot;Error when calling SayHello: %s&quot;, err)<br>  }<br>  log.Printf(&quot;Response from server: %s&quot;, response.Greeting)<br>}</pre><p>Once again, the break down is pretty straight forward:</p><ul><li>the main function instantiates a client connection, on the TCP port the server is bound to;</li><li>note the defer call to properly close the connection when the function returns;</li><li>the c variable is a client for the the Ping service, that calls the SayHello function, passing a PingMessage to it.</li></ul><p>You can compile your code to get a client binary:</p><pre>$ go build -i -v -o bin/client gitlab.com/pantomath-io/demo-grpc/client</pre><h3>Make them talk</h3><p>You’ve just built a client and a server, so fire them in two terminals to test them:</p><pre>$ bin/server<br>2006/01/02 15:04:05 Receive message foo</pre><pre>$ bin/client<br>2006/01/02 15:04:05 Response from server: bar</pre><h3>Tool to ease your life</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-grpc/blob/init-makefile/Makefile"><em>init-makefile</em></a></p><p>Now the API, the client and the server are working, you may prefer to have a Makefile to compile the code, clean your folder, manage dependencies, etc.</p><p>So create this <a href="https://gitlab.com/pantomath-io/demo-grpc/blob/init-makefile/Makefile">Makefile</a> at the root of the project folder. Explaining this file is beyond the scope of this post, and it mostly uses compile command you already spawned previously.</p><p>To use the Makefile , try calling the following:</p><pre>$ make help<br>api                            Auto-generate grpc go sources<br>build_client                   Build the binary file for client<br>build_server                   Build the binary file for server<br>clean                          Remove previous builds<br>dep                            Get the dependencies<br>help                           Display this help screen</pre><h3>Secure the communication</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-grpc/tree/add-ssl"><em>add-ssl</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_WFayrFR6ciCOLn8fWI7g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/-4AFJ5yujcE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nathaniel Tetteh</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The client and the servers talk to each other, over <a href="https://http2.github.io/">HTTP/2</a> (transport layer on gRPC). The messages are binary data(thanks to Protobuf), but the communication is in plaintext. Fortunately, gRPC has SSL/TLS integration, that can be used to authenticate the server (from the client’s perspective), and to encrypt message exchanges.</p><p>You don’t need to change anything to the protocol: it remains the same. The changes take place in the gRPC object creation, on both client and server side. Note that if you change only one side, the connection won’t work.</p><p>Before you change anything in the code, you need to create a <a href="https://en.wikipedia.org/wiki/Self-signed_certificate">self-signed SSL certificate</a>. The purpose of this post is not to explain how to do that, but the <a href="https://www.openssl.org/docs/manmaster/man1/">official OpenSSL documentation</a> (<a href="https://www.openssl.org/docs/manmaster/man1/genrsa.html">genrsa</a>, <a href="https://www.openssl.org/docs/manmaster/man1/req.html">req</a>, <a href="https://www.openssl.org/docs/manmaster/man1/x509.html">x509</a>) can answer your question about it (DigitalOcean also has a <a href="https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs">nice and complete tutorial</a> about it). Meanwhile, you can just use the files provided in the <a href="https://gitlab.com/pantomath-io/demo-grpc/tree/add-ssl/cert">cert</a> folder. The following commands have been used to generate the files:</p><pre>$ openssl genrsa -out cert/server.key 2048<br>$ openssl req -new -x509 -sha256 -key cert/server.key -out cert/server.crt -days 3650<br>$ openssl req -new -sha256 -key cert/server.key -out cert/server.csr<br>$ openssl x509 -req -sha256 -in cert/server.csr -signkey cert/server.key -out cert/server.crt -days 3650</pre><p>You can proceed and update the server definition to use the certificate and the key:</p><pre>package main</pre><pre>import (<br>  &quot;fmt&quot;<br>  &quot;log&quot;<br>  &quot;net&quot;</pre><pre>  &quot;gitlab.com/pantomath-io/demo-grpc/api&quot;<br>  &quot;google.golang.org/grpc&quot;<br>  &quot;google.golang.org/grpc/credentials&quot;<br>)</pre><pre>// main starts a gRPC server and waits for connection<br>func main() {<br>  // create a listener on TCP port 7777<br>  lis, err := net.Listen(&quot;tcp&quot;, fmt.Sprintf(&quot;%s:%d&quot;, &quot;localhost&quot;, 7777))<br>  if err != nil {<br>    log.Fatalf(&quot;failed to listen: %v&quot;, err)<br>  }</pre><pre>  // create a server instance<br>  s := api.Server{}</pre><pre>  // Create the TLS credentials<br>  creds, err := credentials.NewServerTLSFromFile(&quot;cert/server.crt&quot;, &quot;cert/server.key&quot;)<br>  if err != nil {<br>    log.Fatalf(&quot;could not load TLS keys: %s&quot;, err)<br>  }</pre><pre>  // Create an array of gRPC options with the credentials<br>  opts := []grpc.ServerOption{grpc.Creds(creds)}</pre><pre>  // create a gRPC server object<br>  grpcServer := grpc.NewServer(opts...)</pre><pre>  // attach the Ping service to the server<br>  api.RegisterPingServer(grpcServer, &amp;s)</pre><pre>  // start the server<br>  if err := grpcServer.Serve(lis); err != nil {<br>    log.Fatalf(&quot;failed to serve: %s&quot;, err)<br>  }<br>}</pre><p>So what changed?</p><ul><li>you created a <a href="https://godoc.org/google.golang.org/grpc/credentials">credentials</a> object (called creds) from your certificate and key files;</li><li>you created a <a href="https://godoc.org/google.golang.org/grpc#ServerOption">grpc.ServerOption</a> array and placed your credentials object in it;</li><li>when creating the grpc server, you provided the constructor with you array of grpc.ServerOption;</li><li>you must have noticed that you need to precisely specify the IP you bind your server to, so that the IP matches the FQDN used in the certificate.</li></ul><p>Note that grpc.NewServer() is a variadic function, so you can pass it any number of trailing arguments. You created an array of options so that we can add other options later on.</p><p>If you compile your server now, and use the client you already have, the connection won’t work, and both sides will throw an error.</p><ul><li>the server report the client is not handshaking with TLS:</li></ul><pre>2006/01/02 15:04:05 grpc: Server.Serve failed to complete security handshake from &quot;localhost:64018&quot;: tls: first record does not look like a TLS handshake</pre><ul><li>the client has its connection closed before it can do anything:</li></ul><pre>2006/01/02 15:04:05 transport: http2Client.notifyError got notified that the client transport was broken read tcp localhost:64018-&gt;127.0.0.1:7777: read: connection reset by peer.<br>2006/01/02 15:04:05 Error when calling SayHello: rpc error: code = Internal desc = transport is closing</pre><p>You need to use the exact same certificate file on the client side. So edit the client/main.go file:</p><pre>package main</pre><pre>import (<br>  &quot;log&quot;</pre><pre>  &quot;gitlab.com/pantomath-io/demo-grpc/api&quot;<br>  &quot;golang.org/x/net/context&quot;<br>  &quot;google.golang.org/grpc&quot;<br>  &quot;google.golang.org/grpc/credentials&quot;<br>)</pre><pre>func main() {<br>  var conn *grpc.ClientConn</pre><pre>// Create the client TLS credentials<br>  creds, err := credentials.NewClientTLSFromFile(&quot;cert/server.crt&quot;, &quot;&quot;)<br>  if err != nil {<br>    log.Fatalf(&quot;could not load tls cert: %s&quot;, err)<br>  }</pre><pre>  // Initiate a connection with the server<br>  conn, err = grpc.Dial(&quot;localhost:7777&quot;, grpc.WithTransportCredentials(creds))<br>  if err != nil {<br>    log.Fatalf(&quot;did not connect: %s&quot;, err)<br>  }<br>  defer conn.Close()</pre><pre>  c := api.NewPingClient(conn)</pre><pre>  response, err := c.SayHello(context.Background(), &amp;api.PingMessage{Greeting: &quot;foo&quot;})<br>  if err != nil {<br>    log.Fatalf(&quot;error when calling SayHello: %s&quot;, err)<br>  }<br>  log.Printf(&quot;Response from server: %s&quot;, response.Greeting)<br>}</pre><p>The changes on the client side are pretty much the same as on the server:</p><ul><li>you created a <a href="https://godoc.org/google.golang.org/grpc/credentials">credentials</a> object with the certificate file. Note that the client <strong>do not use</strong> the certificate key, the key is private to the server;</li><li>you added an option to the grpc.Dial() function, using your credentials object. Note that the <a href="https://godoc.org/google.golang.org/grpc#Dial">grpc.Dial()</a> function is also a variadic function, so it accepts any number of options;</li><li>same server note applies for the client: you need to use the same FQDN to connect to the server as the one used in the certificate, or the transport authentication handshake will fail.</li></ul><p>Both sides use credentials, so they should be able to talk just as before, but in an encrypted way. You can compile the code:</p><pre>$ make</pre><p>And run both sides in separate terminals:</p><pre>$ bin/server<br>2006/01/02 15:04:05 Receive message foo</pre><pre>$ bin/client<br>2006/01/02 15:04:05 Response from server: bar</pre><h3>Identify the client</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-grpc/tree/add-auth"><em>add-auth</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hIUb4TpxYkHehxMb7KpEw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/984e1Fk4E04?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">chuttersnap</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Another interesting feature of the gRPC server is the ability to intercept a request from the client. The client can inject information on the transport layer. You can use that feature to identify your client, because the SSL implementation authenticates the server (via the certificate), but not the client (all your clients are using the same certificate).</p><p>So you’ll update the client side to inject metadata on every call (like a login and password), and the server side to check these credentials for every incoming call.</p><p>On the client side, you just need to specify a DialOption on your grpc.Dial() call. But that DialOptionhas some constraints. Edit your client/main.go file:</p><pre>package main</pre><pre>import (<br>  &quot;log&quot;</pre><pre>  &quot;gitlab.com/pantomath-io/demo-grpc/api&quot;<br>  &quot;golang.org/x/net/context&quot;<br>  &quot;google.golang.org/grpc&quot;<br>  &quot;google.golang.org/grpc/credentials&quot;<br>)</pre><pre>// Authentication holds the login/password<br>type Authentication struct {<br>  Login    string<br>  Password string<br>}</pre><pre>// GetRequestMetadata gets the current request metadata<br>func (a *Authentication) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {<br>  return map[string]string{<br>    &quot;login&quot;:    a.Login,<br>    &quot;password&quot;: a.Password,<br>  }, nil<br>}</pre><pre>// RequireTransportSecurity indicates whether the credentials requires transport security<br>func (a *Authentication) RequireTransportSecurity() bool {<br>  return true<br>}</pre><pre>func main() {<br>  var conn *grpc.ClientConn</pre><pre>// Create the client TLS credentials<br>  creds, err := credentials.NewClientTLSFromFile(&quot;cert/server.crt&quot;, &quot;&quot;)<br>  if err != nil {<br>    log.Fatalf(&quot;could not load tls cert: %s&quot;, err)<br> }</pre><pre>  // Setup the login/pass<br>  auth := Authentication{<br>    Login:    &quot;john&quot;,<br>    Password: &quot;doe&quot;,<br>  }</pre><pre>  // Initiate a connection with the server<br>  conn, err = grpc.Dial(&quot;localhost:7777&quot;, grpc.WithTransportCredentials(creds), grpc.WithPerRPCCredentials(&amp;auth))<br>  if err != nil {<br>    log.Fatalf(&quot;did not connect: %s&quot;, err)<br>   }<br>   defer conn.Close()</pre><pre>  c := api.NewPingClient(conn)</pre><pre>  response, err := c.SayHello(context.Background(), &amp;api.PingMessage{Greeting: &quot;foo&quot;})<br>  if err != nil {<br>    log.Fatalf(&quot;error when calling SayHello: %s&quot;, err)<br>  }<br>  log.Printf(&quot;Response from server: %s&quot;, response.Greeting)<br>}</pre><ul><li>You define a struct to hold the collection on fields you want to inject in your rcp calls. In our case, just a login and password, but you can imagine any fields you want;</li><li>The auth variable holds the values you’ll be using;</li><li>You use grpc.WithPerRPCCredentials() function to create a DialOption object to the grpc.Dial() function;</li><li>Note that the <a href="https://godoc.org/google.golang.org/grpc#WithPerRPCCredentials">grpc.WithPerRPCCredentials()</a> function takes an interface as parameter, so your Authentication structure should comply to that interface. From the <a href="https://godoc.org/google.golang.org/grpc/credentials#PerRPCCredentials">documentation</a>, you know you should implement 2 methods on your structure: GetRequestMetadata and RequireTransportSecurity.</li><li>So you define GetRequestMetadata function that just returns a map of your Authentication structure;</li><li>And finally, you define RequireTransportSecurity function, that tells your grpc client if it should inject metadata at the transport level. In our current case, it always returns true, but you could have it return the value of a configuration boolean, for instance.</li></ul><p>The client is up to push extra data during its calls to the server, but the server does not care, right now. So you need to tell him to check these metadata. Open server/main.go and update it:</p><pre>package main</pre><pre>import (<br>  &quot;fmt&quot;<br>  &quot;log&quot;<br>  &quot;net&quot;<br>  &quot;strings&quot;</pre><pre>  &quot;golang.org/x/net/context&quot;</pre><pre>  &quot;gitlab.com/pantomath-io/demo-grpc/api&quot;<br>  &quot;google.golang.org/grpc&quot;<br>  &quot;google.golang.org/grpc/credentials&quot;<br>  &quot;google.golang.org/grpc/metadata&quot;<br>)</pre><pre>// private type for Context keys<br>type contextKey int</pre><pre>const (<br>  clientIDKey contextKey = iota<br>)</pre><pre>// authenticateAgent check the client credentials<br>func authenticateClient(ctx context.Context, s *api.Server) (string, error) {<br>  if md, ok := metadata.FromIncomingContext(ctx); ok {<br>    clientLogin := strings.Join(md[&quot;login&quot;], &quot;&quot;)<br>    clientPassword := strings.Join(md[&quot;password&quot;], &quot;&quot;)</pre><pre>    if clientLogin != &quot;john&quot; {<br>      return &quot;&quot;, fmt.Errorf(&quot;unknown user %s&quot;, clientLogin)<br>    }<br>    if clientPassword != &quot;doe&quot; {<br>      return &quot;&quot;, fmt.Errorf(&quot;bad password %s&quot;, clientPassword)<br>    }</pre><pre>    log.Printf(&quot;authenticated client: %s&quot;, clientLogin)<br>    return &quot;42&quot;, nil<br>  }</pre><pre>  return &quot;&quot;, fmt.Errorf(&quot;missing credentials&quot;)<br>}</pre><pre>// unaryInterceptor calls authenticateClient with current context<br>func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {<br>  s, ok := info.Server.(*api.Server)<br>  if !ok {<br>    return nil, fmt.Errorf(&quot;unable to cast server&quot;)<br>  }<br>  clientID, err := authenticateClient(ctx, s)<br>  if err != nil {<br>    return nil, err<br>  }</pre><pre>  ctx = context.WithValue(ctx, clientIDKey, clientID)<br>  return handler(ctx, req)<br>}</pre><pre>// main start a gRPC server and waits for connection<br>func main() {<br>  // create a listener on TCP port 7777<br>  lis, err := net.Listen(&quot;tcp&quot;, fmt.Sprintf(&quot;%s:%d&quot;, &quot;localhost&quot;, 7777))<br>  if err != nil {<br>    log.Fatalf(&quot;failed to listen: %v&quot;, err)<br>  }</pre><pre>  // create a server instance<br>  s := api.Server{}</pre><pre>  // Create the TLS credentials<br>  creds, err := credentials.NewServerTLSFromFile(&quot;cert/server.crt&quot;, &quot;cert/server.key&quot;)<br>  if err != nil {<br>    log.Fatalf(&quot;could not load TLS keys: %s&quot;, err)<br>  }</pre><pre>  // Create an array of gRPC options with the credentials<br>  opts := []grpc.ServerOption{grpc.Creds(creds),<br>    grpc.UnaryInterceptor(unaryInterceptor)}</pre><pre>  // create a gRPC server object<br>  grpcServer := grpc.NewServer(opts...)</pre><pre>  // attach the Ping service to the server<br>  api.RegisterPingServer(grpcServer, &amp;s)</pre><pre>  // start the server<br>  if err := grpcServer.Serve(lis); err != nil {<br>    log.Fatalf(&quot;failed to serve: %s&quot;, err)<br>  }<br>}</pre><p>Once again, let me break down this for you:</p><ul><li>you add a new grpc.ServerOption to the array you created before (see why it’s an array, now?): <a href="https://godoc.org/google.golang.org/grpc#UnaryInterceptor">grpc.UnaryInterceptor</a>. And you pass a <a href="https://godoc.org/google.golang.org/grpc#UnaryServerInterceptor">reference to a function</a> to that function, so it knows who to call. The rest of the main code does not change;</li><li>you have to define the unaryInterceptor function, considering it gets a bunch of parameters:</li></ul><ol><li>a <a href="https://godoc.org/golang.org/x/net/context">context.Context</a> object, containing your data, and that will exist during all the lifetime of the request;</li><li>an interface{} which is the inbound parameter of the RPC call;</li><li>a <a href="https://godoc.org/google.golang.org/grpc#UnaryServerInfo">UnaryServerInfo</a> struct which contains a bunch of information about the call (such as the Server abstraction object, and the method call by the client);</li><li>a <a href="https://godoc.org/google.golang.org/grpc#UnaryHandler">UnaryHandler</a> struct which is the handler invoked by UnaryServerInterceptor to complete the normal execution of a unary RPC (i.e. an handler to what happens when the UnaryInterceptor returns).</li></ol><ul><li>the unaryInterceptor function makes sure the grpc.UnaryServerInfo has the right server abstraction, and call the authentication function, authenticateClient;</li><li>you define the authenticateClient function with your authentication logic — very very simple in this example. Note that it receives the context.Context as parameter, and extract the metadata from it. It checks the user, and returns its ID (in the form of a string, with a hypothetical error.</li><li>if the unaryInterceptor gets no error from the authenticateClient function, it pushes the clientID in the context.Context object, so that the rest of the execution chain can use it (remember the handler gets the context.Context object as parameter?);</li><li>Note that you created your type and const to reference the clientID in the context.Context map. This is just an handy way to avoid naming conflict and to allow constant reference.</li></ul><p>You can compile the code:</p><pre>$ make</pre><p>And run both sides in separate terminals:</p><pre>$ bin/server<br>2006/01/02 15:04:05 authenticated client: john<br>2006/01/02 15:04:05 Receive message foo</pre><pre>$ bin/client<br>2006/01/02 15:04:05 Response from server: bar</pre><p>Obviously, your authentication logic will probably be smarter, comparing credentials against a database. The easy part of it is: your authentication function gets your abstraction of a Server, and this structure can hold your database handler.</p><h3>Open to REST</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-grpc/tree/add-rest"><em>add-rest</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpCAELNImICQxw8UxA0bsA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/nNPONh2aXeQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rio Hodges</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>One last thing: you have a pretty neat server, client and protocol; serialized, encrypted and authenticated. But there is a important limit: your client needs to be gRPC compliant, that is be in the list of <a href="https://grpc.io/about/#osp">supported platforms</a>. To avoid that limit, we can open the server to a REST gateway, allowing REST clients to perform requests it. Luckily, there is a gRPC <a href="https://github.com/grpc-ecosystem/grpc-gateway">protoc plugin</a> to generate a reverse-proxy server which translates a RESTful JSON API into gRPC. We can use a few line of pure Go code to serve that reverse-proxy.</p><p>So edit your <a href="https://gitlab.com/pantomath-io/demo-grpc/blob/add-rest/api/api.proto">api/api.proto</a> file to add some extra information:</p><pre>syntax = &quot;proto3&quot;;<br>package api;</pre><pre>import &quot;google/api/annotations.proto&quot;;</pre><pre>message PingMessage {<br>  string greeting = 1;<br>}</pre><pre>service Ping {<br>  rpc SayHello(PingMessage) returns (PingMessage) {<br>    option (google.api.http) = {<br>      post: &quot;/1/ping&quot;<br>      body: &quot;*&quot;<br>    };<br>  }<br>}</pre><p>The annotations.proto import allows protoc to understand the option set later in the file. And the option defines that method and the path to the endpoint.</p><p>Update the <a href="https://gitlab.com/pantomath-io/demo-grpc/blob/add-rest/Makefile">Makefile</a> to add a target for this new Protobuf compilation:</p><pre>SERVER_OUT := &quot;bin/server&quot;<br>CLIENT_OUT := &quot;bin/client&quot;<br>API_OUT := &quot;api/api.pb.go&quot;<br>API_REST_OUT := &quot;api/api.pb.gw.go&quot;<br>PKG := &quot;gitlab.com/pantomath-io/demo-grpc&quot;<br>SERVER_PKG_BUILD := &quot;${PKG}/server&quot;<br>CLIENT_PKG_BUILD := &quot;${PKG}/client&quot;<br>PKG_LIST := $(shell go list ${PKG}/... | grep -v /vendor/)</pre><pre>.PHONY: all api server client</pre><pre>all: server client</pre><pre>api/api.pb.go: api/api.proto<br>  <a href="http://twitter.com/protoc">@protoc</a> -I api/ \<br>    -I${GOPATH}/src \<br>    -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \<br>    --go_out=plugins=grpc:api \<br>    api/api.proto</pre><pre>api/api.pb.gw.go: api/api.proto<br>  <a href="http://twitter.com/protoc">@protoc</a> -I api/ \<br>    -I${GOPATH}/src \<br>    -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \<br>    --grpc-gateway_out=logtostderr=true:api \<br>    api/api.proto</pre><pre>api: api/api.pb.go api/api.pb.gw.go ## Auto-generate grpc go sources</pre><pre>dep: ## Get the dependencies<br>  <a href="http://twitter.com/go">@go</a> get -v -d ./...</pre><pre>server: dep api ## Build the binary file for server<br>  <a href="http://twitter.com/go">@go</a> build -i -v -o $(SERVER_OUT) $(SERVER_PKG_BUILD)</pre><pre>client: dep api ## Build the binary file for client<br>  <a href="http://twitter.com/go">@go</a> build -i -v -o $(CLIENT_OUT) $(CLIENT_PKG_BUILD)</pre><pre>clean: ## Remove previous builds<br>  <a href="http://twitter.com/rm">@rm</a> $(SERVER_OUT) $(CLIENT_OUT) $(API_OUT) $(API_REST_OUT)</pre><pre>help: ## Display this help screen<br>  <a href="http://twitter.com/grep">@grep</a> -E &#39;^[a-zA-Z_-]+:.*?## .*$$&#39; $(MAKEFILE_LIST) | sort | awk &#39;BEGIN {FS = &quot;:.*?## &quot;}; {printf &quot;\033[36m%-30s\033[0m %s\n&quot;, $$1, $$2}&#39;</pre><p>Generate the Go code for the gateway (the file api/api.pb.gw.go will be generated — just as api/api.pb.go, don’t edit it, it will be updated by compilation):</p><pre>$ make api</pre><p>The change on the server side is more important. The grpc.Serve() function is a blocking function, that returns only on error (or can get killed by a signal). As we need to start another server (the REST interface), we need this call to be non-blocking. Fortunately, we have <strong>goroutines</strong> just for that. And there is a trick on the authentication. As the REST gateway is just a reverse-proxy, it acts as a client from the gRPC perspective. Thus it needs to use a WithPerRPCCredentials option when dialing the server.</p><p>Head to your <a href="https://gitlab.com/pantomath-io/demo-grpc/blob/add-rest/server/main.go">server/main.go</a> file:</p><pre>package main</pre><pre>import (<br>  &quot;fmt&quot;<br>  &quot;log&quot;<br>  &quot;net&quot;<br>  &quot;net/http&quot;<br>  &quot;strings&quot;</pre><pre>  &quot;github.com/grpc-ecosystem/grpc-gateway/runtime&quot;<br>  &quot;golang.org/x/net/context&quot;<br>  &quot;gitlab.com/pantomath-io/demo-grpc/api&quot;<br>  &quot;google.golang.org/grpc&quot;<br>  &quot;google.golang.org/grpc/credentials&quot;<br>  &quot;google.golang.org/grpc/metadata&quot;<br>)</pre><pre>// private type for Context keys<br>type contextKey int</pre><pre>const (<br>  clientIDKey contextKey = iota<br>)</pre><pre>func credMatcher(headerName string) (mdName string, ok bool) {<br>  if headerName == &quot;Login&quot; || headerName == &quot;Password&quot; {<br>    return headerName, true<br>  }<br>  return &quot;&quot;, false<br>}</pre><pre>// authenticateAgent check the client credentials<br>func authenticateClient(ctx context.Context, s *api.Server) (string, error) {<br>  if md, ok := metadata.FromIncomingContext(ctx); ok {<br>    clientLogin := strings.Join(md[&quot;login&quot;], &quot;&quot;)<br>    clientPassword := strings.Join(md[&quot;password&quot;], &quot;&quot;)</pre><pre>    if clientLogin != &quot;john&quot; {<br>      return &quot;&quot;, fmt.Errorf(&quot;unknown user %s&quot;, clientLogin)<br>    }<br>    if clientPassword != &quot;doe&quot; {<br>      return &quot;&quot;, fmt.Errorf(&quot;bad password %s&quot;, clientPassword)<br>    }</pre><pre>    log.Printf(&quot;authenticated client: %s&quot;, clientLogin)<br>    return &quot;42&quot;, nil<br>  }<br>  return &quot;&quot;, fmt.Errorf(&quot;missing credentials&quot;)<br>}</pre><pre>// unaryInterceptor call authenticateClient with current context<br>func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {<br>  s, ok := info.Server.(*api.Server)<br>  if !ok {<br>    return nil, fmt.Errorf(&quot;unable to cast server&quot;)<br>  }<br>  clientID, err := authenticateClient(ctx, s)<br>  if err != nil {<br>    return nil, err<br>  }</pre><pre>  ctx = context.WithValue(ctx, clientIDKey, clientID)<br>  return handler(ctx, req)<br>}</pre><pre>func startGRPCServer(address, certFile, keyFile string) error {<br>  // create a listener on TCP port<br>  lis, err := net.Listen(&quot;tcp&quot;, address)<br>  if err != nil {<br>    return fmt.Errorf(&quot;failed to listen: %v&quot;, err)<br>  }</pre><pre>  // create a server instance<br>  s := api.Server{}</pre><pre>  // Create the TLS credentials<br>  creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)<br>  if err != nil {<br>    return fmt.Errorf(&quot;could not load TLS keys: %s&quot;, err)<br>  }</pre><pre>  // Create an array of gRPC options with the credentials<br>  opts := []grpc.ServerOption{grpc.Creds(creds),<br>    grpc.UnaryInterceptor(unaryInterceptor)}</pre><pre>  // create a gRPC server object<br>  grpcServer := grpc.NewServer(opts...)</pre><pre>  // attach the Ping service to the server<br>  api.RegisterPingServer(grpcServer, &amp;s)</pre><pre>  // start the server<br>  log.Printf(&quot;starting HTTP/2 gRPC server on %s&quot;, address)<br>  if err := grpcServer.Serve(lis); err != nil {<br>    return fmt.Errorf(&quot;failed to serve: %s&quot;, err)<br>  }</pre><pre>  return nil<br>}</pre><pre>func startRESTServer(address, grpcAddress, certFile string) error {<br>  ctx := context.Background()<br>  ctx, cancel := context.WithCancel(ctx)<br>  defer cancel()</pre><pre>  mux := runtime.NewServeMux(runtime.WithIncomingHeaderMatcher(credMatcher))</pre><pre>  creds, err := credentials.NewClientTLSFromFile(certFile, &quot;&quot;)<br>  if err != nil {<br>    return fmt.Errorf(&quot;could not load TLS certificate: %s&quot;, err)<br>  }</pre><pre>  // Setup the client gRPC options<br>  opts := []grpc.DialOption{grpc.WithTransportCredentials(creds)}</pre><pre>  // Register ping<br>  err = api.RegisterPingHandlerFromEndpoint(ctx, mux, grpcAddress, opts)<br>  if err != nil {<br>    return fmt.Errorf(&quot;could not register service Ping: %s&quot;, err)<br>  }</pre><pre>  log.Printf(&quot;starting HTTP/1.1 REST server on %s&quot;, address)<br>  http.ListenAndServe(address, mux)</pre><pre>  return nil<br>}</pre><pre>// main start a gRPC server and waits for connection<br>func main() {<br>  grpcAddress := fmt.Sprintf(&quot;%s:%d&quot;, &quot;localhost&quot;, 7777)<br>  restAddress := fmt.Sprintf(&quot;%s:%d&quot;, &quot;localhost&quot;, 7778)<br>  certFile := &quot;cert/server.crt&quot;<br>  keyFile := &quot;cert/server.key&quot;</pre><pre>  // fire the gRPC server in a goroutine<br>  go func() {<br>    err := startGRPCServer(grpcAddress, certFile, keyFile)<br>    if err != nil {<br>      log.Fatalf(&quot;failed to start gRPC server: %s&quot;, err)<br>    }<br>  }()</pre><pre>  // fire the REST server in a goroutine<br>  go func() {<br>    err := startRESTServer(restAddress, grpcAddress, certFile)<br>    if err != nil {<br>      log.Fatalf(&quot;failed to start gRPC server: %s&quot;, err)<br>    }<br>  }()</pre><pre>  // infinite loop<br>  log.Printf(&quot;Entering infinite loop&quot;)<br>  select {}<br>}</pre><p>So what happened?</p><ul><li>you moved all the code for the gRPC server creation in a goroutine with a dedicated function (startGRPCServer), so it does not block the main;</li><li>you create a new goroutine with a dedicated function (startRESTServer) where you create an HTTP/1.1 server;</li><li>in startRESTServer where you create the REST gateway, you start by getting the context.Context background object (i.e. the root of the context tree). Then, you create a request multiplexer object, mux, with an option: runtime.WithIncomingHeaderMatcher. This option takes a function reference as parameter, credMatch, and is called for every HTTP header from the incoming request. The function evaluates whether or not the HTTP header should be passed to the gRPC context;</li><li>you defined the credMatch function to match the credentials header, allowing them to be metadata in the gRPC context. This is how you have your authentication working, because the reverse-proxy uses the HTTP headers it receives when it connects to the gRPC server;</li><li>you also create a credentials.NewClientTLSFromFile, to be used as a grpc.DialOption, just like you did in the client side;</li><li>you register your api endpoint, i.e. you make the link between your multiplexer, you gRPC server, using the context and the gRPC options;</li><li>and finally, you start an HTTP/1.1 server, and wait for incoming connections;</li><li>aside to your goroutine, you use a blocking select call, so that your program does not end right away.</li></ul><p>Now build the whole project, so you can test the REST interface:</p><pre>$ make</pre><p>And run both sides in separate terminals:</p><pre>$ bin/server<br>2006/01/02 15:04:05 Entering infinite loop<br>2006/01/02 15:04:05 starting HTTP/1.1 REST server on localhost:7778<br>2006/01/02 15:04:05 starting HTTP/2 gRPC server on localhost:7777<br>2006/01/02 15:04:05 authenticated client: john<br>2006/01/02 15:04:05 Receive message foo</pre><pre>$ curl -H &quot;login:john&quot; -H &quot;password:doe&quot; -X POST -d &#39;{&quot;greeting&quot;:&quot;foo&quot;}&#39; &#39;<a href="http://localhost:7778/1/ping&#39;">http://localhost:7778/1/ping&#39;</a><br>{&quot;greeting&quot;:&quot;bar&quot;}</pre><h3>One last swag…</h3><p><em>git tag: </em><a href="https://gitlab.com/pantomath-io/demo-grpc/tree/add-swagger"><em>add-swagger</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lg78b_518eFveLDKDsA5hQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ETNcibiiWOs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lorenzo Castagnone</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The REST gateway is cool, but it would be even cooler to generate documentation from it, right?</p><p>You can do that for free, using a <a href="https://github.com/grpc-ecosystem/grpc-gateway">protoc plugin</a> to generate a <a href="https://swagger.io/">swagger</a> json file:</p><pre>protoc -I api/ \<br>  -I${GOPATH}/src \<br>  -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \<br>  --swagger_out=logtostderr=true:api \<br>  api/api.proto</pre><p>This will generate a api/api.swagger.json file. As all generated code from Protobuf compilation, you should not edit it, but you can use it, and it can update it when you change your definition file.</p><p>You can add the compilation command in the <a href="https://gitlab.com/pantomath-io/demo-grpc/blob/add-swagger/Makefile">Makefile</a>.</p><h3>Conclusion</h3><p>You have a fully functional gRPC client and server, with SSL encryption &amp; authentication, client identification, and a REST gateway (with its swagger file). Where to go from here?</p><p>You can push a little on the REST gateway, to make it HTTPS instead of HTTP. You can obviously add more complex data structure on your Protobuf, alongside with more service. You can benefit from HTTP/2 features, such as <a href="https://grpc.io/docs/guides/concepts.html#bidirectional-streaming-rpc">streaming</a>, either from client to server, or from server to client, or bidirectional (but that’s only for gRPC, not for the REST, based on HTTP/1.1).</p><p><em>Many thanks to </em><a href="https://medium.com/u/177d8b64f64f"><em>Charles Francoise</em></a><em> who co-wrote this paper and </em><a href="https://gitlab.com/pantomath-io/demo-grpc"><em>https://gitlab.com/pantomath-io/demo-grpc</em></a><em>.</em></p><p><em>We are currently working on Pantomath. Pantomath is a modern, open-source monitoring solution, built for performance, that bridges the gaps across all levels of your company. The well-being of your infrastructure is everyone’s business. Keep up with the project : </em><a href="http://goo.gl/tcxtXq"><em>goo.gl/tcxtXq</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd20045fa1c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pantomath/how-we-use-grpc-to-build-a-client-server-system-in-go-dd20045fa1c2">How we use gRPC to build a client/server system in Go</a> was originally published in <a href="https://medium.com/pantomath">Pantomath</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>