<?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[Stories by Lucas Henry on Medium]]></title>
        <description><![CDATA[Stories by Lucas Henry on Medium]]></description>
        <link>https://medium.com/@lucas.henry?source=rss-97fd91b937f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VeezptXVANESPQRvcbG6TA.jpeg</url>
            <title>Stories by Lucas Henry on Medium</title>
            <link>https://medium.com/@lucas.henry?source=rss-97fd91b937f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:32:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucas.henry/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Go with gRPC, SQL, Dependency Injection(Wire) + standard project structure, and more: Introduction.]]></title>
            <link>https://medium.com/@lucas.henry/go-with-grpc-sql-dependency-injection-wire-standard-project-structure-and-more-introduction-f015d7d4ac7a?source=rss-97fd91b937f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f015d7d4ac7a</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Lucas Henry]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 18:10:01 GMT</pubDate>
            <atom:updated>2022-03-14T18:17:04.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_9DGTDXFw4HC8UlOLcFUQ.png" /></figure><p>As a passionate about scalable project structure, with a robust NestJS background, when I began working with Go, I missed some of the default features of this framework, like configuration module, global services, database connection, dependencies injections, etc. so I asked myself if a can apply the same techniques in Go without any framework and the simplicity of Go… and I got it!</p><p>Welcome to the first article of this series. Take a cafe because here we go!</p><p>We are going to create a basic login gRPC API, and when you finish, you will know how standard API features are implemented in Go like:</p><p>Server Configuration and start gRPC server:</p><ul><li>Protocol Buffer with <a href="https://github.com/bufbuild/buf">Buf</a> and Makefile</li><li>Go Server configuration with <a href="https://github.com/spf13/viper">Viper</a></li><li>Start gRPC server</li></ul><p>Database and common project structure:</p><ul><li>Use <a href="https://gorm.io/index.html">GORM</a> to connect to Postgres and migrate your models</li><li>Create project structure gRPC -&gt; Service -&gt; Repository -&gt; DAO</li><li>Use Wire to manage dependencies</li></ul><p>Basic login gRPC API with JWT and Evans CLI :</p><ul><li>Implement user creation</li><li>Implements Hash/Check Password</li><li>Use Evans CLI client for user creation</li></ul><p>gRPC interceptors, global services, and private/public RPC methods guarded with JWT:</p><ul><li>Implement interceptors(Authorization interceptor &amp; logging interceptor)</li><li>Create a global service in using context</li><li>Register public and private gRPC methods with interceptors</li><li>Implements method service + JWT for guard gRPC method</li></ul><h3>Protocol Buffer, Configuration, and start gRPC server</h3><p>We are going to start with Protocol Buffer with <a href="https://github.com/bufbuild/buf">Buf</a> and Makefile for automatization</p><p>Create the project folder workspace:</p><pre>$ mkdir logic_grpc &amp;&amp; cd logic_grpc</pre><p>Install protocol buffer compiler protoc, <a href="https://grpc.io/docs/protoc-installation/">here for more details</a></p><pre>$ brew install protobuf<br>$ protoc --version  <em># Ensure compiler version is 3+</em></pre><p><a href="https://grpc.io/docs/languages/go/quickstart/">Install Go gRPC compiler plugins</a></p><pre>$ go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.26<br>$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1 </pre><p>Update your PATH so that the protoc compiler can find the plugins:</p><pre>$ export PATH=&quot;$PATH:$HOME/.local/bin&quot;</pre><p>Nice! now let&#39;s define our protocol buffer file. <strong>Create a folder at the root level called api, and inside the folder, create a file named auth.proto </strong>and paste the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4840c14596ffd54682679326d9eeaec2/href">https://medium.com/media/4840c14596ffd54682679326d9eeaec2/href</a></iframe><p>Here we have two gRPC services, <strong>UsersServices </strong>with two methods, <em>CreateUser</em> and <em>GetUserInfo</em>(in the future, this method will be guarded with some AuthGuard logic) and <strong>LoginService</strong> with Login method.</p><p>We need to compile this file to generate go gRPC server/client files and code for populating, serializing, and retrieving request and response messages types.</p><p>We can run this “<em>beautiful</em>” command<strong> inside the ./api</strong> folder</p><pre>$ protoc --go_out=. --go_opt=paths=source_relative \<br> --go-grpc_out=. --go-grpc_opt=paths=source_relative \<br>auth.proto</pre><blockquote>⚠️ <a href="https://gist.github.com/vsouza/77e6b20520d07652ed7d">If you have problems with this command, ensure you have the correct export of GOPATH and GOROOT in your path.</a></blockquote><p>Ok, right, I know what you are thinking, “I need to run this command every time I want to compile my protofile? what if we need to add more configurations? ” and the answer is… Yes :( you need to run this command every time you want to compile your protofile… and if you need to add more configuration, the complexity of this command line will grow.</p><p>But don&#39;t worry, I got you covered. To scale up this workflow, we can use Buf. This is a CLI for compiling the protobuffers adding compiler plugins, templates, and more in a developer-friendly .yaml file</p><p>Install <a href="https://github.com/bufbuild/buf">Buf</a>:</p><pre>$ brew install bufbuild/buf/buf</pre><p>Create a buf configuration file <strong>inside ./api folder called buf.gen.yaml</strong> and copy this gist</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c0816c53987b6b4493ad6481e885dea/href">https://medium.com/media/4c0816c53987b6b4493ad6481e885dea/href</a></iframe><p>Take a minute and compare the previous command and this buf file.</p><blockquote>💡 Attention with the <strong>out: ../pkg </strong>configuration(line 4 and 8), <strong>now we are going to leave all our generated profiles in a folder called pkg</strong></blockquote><p>Easy! Now we can compile our protofiles by running this simple command inside api folder</p><pre>$ buf generate</pre><p>Alright! Now you know how to use Buf ⭐. For more information, read the <a href="https://github.com/bufbuild/buf">docs</a></p><h4><strong>Startup the server</strong></h4><p>First, create a go module</p><pre>$ go mod init logic_grpc</pre><p>Then create a main.go and in the <strong>inside ./cmd folder</strong></p><pre>$ mkdir cmd; touch cmd/main.go</pre><p>Now copy this file in your main.go file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/579358ca69278dadf6b0511949b02644/href">https://medium.com/media/579358ca69278dadf6b0511949b02644/href</a></iframe><blockquote>You will have one import error because <strong><em>google.golang.org/grpc</em></strong><em> </em>import is not added in your go module. To match the imports of the source code with the imports of the package, we can run this in the root workspace</blockquote><pre>$ go mod tidy</pre><p>Well done. Now lets me explain this code… First, we need to create a listener <strong>with TCP network type</strong> on the <strong>default gRPC port 50051 </strong>and handle the error. Then create a new server with <em>grpc.NewServer() </em>and use the listener to serve the gRPC server and handle the error again. No more, no less</p><blockquote>🤔 How can I implement the services defined in the protobuf file? We will see this topic in the future, but spoiler, you need an interface of the server service (LoginService and UsersService) and implement the methods of these services, but that is enough for now!</blockquote><p>To run de gRPC server, execute</p><pre>$ go run main</pre><p>But what if we need to add more flags for running our app after some time?</p><p>We can automatize this with Makefile and take advantage of this file to automate the jobs of <strong>generating</strong> protobuffers stub/serialization, <strong>cleaning</strong> the generating files, and <strong>building</strong> the project.</p><p>Create a new file in the root level named Makefile and then copy this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/454336889971f0c58e904cb0dfc65d81/href">https://medium.com/media/454336889971f0c58e904cb0dfc65d81/href</a></iframe><p>Now we can run make run to run our project or make generate to generate code with buf, excellent.</p><blockquote>🤔 <a href="https://stackoverflow.com/questions/2145590/what-is-the-purpose-of-phony-in-a-makefile">What is the purpose of phony in a makefile</a></blockquote><h4><strong>Configuration</strong></h4><p>Standard project configurations always use .env files, centralized cloud configurations, or some human-read config files like .json or .yaml. We can use <a href="https://github.com/spf13/viper">Viper</a> to fetch these config files and initialize your API configuration in Go.</p><p>Install <a href="https://github.com/spf13/viper">Viper</a> and update your package</p><pre>$ go get github.com/spf13/viper; go mod tidy</pre><p>Now let&#39;s create a config.yaml file in your root app level with some server configuration</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48f7f49ebd4366c9abe5cb692c4db5c6/href">https://medium.com/media/48f7f49ebd4366c9abe5cb692c4db5c6/href</a></iframe><p>Then create an <strong>internal folder</strong> and a <strong>config folder</strong> inside with a <strong>config.go file</strong></p><pre>$ mkdir -p internal/config; touch internal/config/config.go</pre><p>In this config.go file. We will define an application config interface and implement it later with Viper. We use an interface because if tomorrow we decide to change de config implementation is simply as changing de viper config initialization for other packages or native config implementation.</p><blockquote><strong>The idea is that our application only depends on the config interface, and that does not depend on the concrete implementation.</strong></blockquote><p>Let&#39;s define our domain interface and types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e98fc148e077d9afbe35418d7e86cea5/href">https://medium.com/media/e98fc148e077d9afbe35418d7e86cea5/href</a></iframe><p><strong>Config</strong> is the interface that will be implemented with Viper, which only has two methods,<em> GetConfig()</em> and <em>GetServerConfig()</em>. In the <strong>ServerConfig</strong> struct, we define our server configuration variables, and <strong>config</strong> is a convenient struct for storing different kinds of app configs, for example, database config and JWT configs.</p><p>Using Viper and implementing the Config interface is simple. First, create a viper.go file in the config directory and copy this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db0679d8b8c3570be127f5454a11be35/href">https://medium.com/media/db0679d8b8c3570be127f5454a11be35/href</a></iframe><p>Then run <strong>go mod tidy </strong>if you have an import error, and if you throw some mistake, just read the instruction in the logs, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*1tqTbE7L4u9AnApaXpfQjg.png" /><figcaption>Common Viper Error</figcaption></figure><p>Just run</p><pre>$ go mod tidy -go=1.16 &amp;&amp; go mod tidy -go=1.17</pre><p>Nice work! The viper code maybe looks a bit rough but is very easy to follow.<br>We have a <strong>ViperConfigInit </strong>function<strong> </strong>that <strong>returns a Config struct</strong>. If you are an OOP guy like me, we can say: “ViperConfigInit is the ViperConfig object constructor.” The constructor uses viper to add the config path to viper, then sets the config file name, in this case, “config”.</p><blockquote>💡 Remember you already have created a config.yaml in your root app-level, and this is the reason for the “../” in AddConfigPath().</blockquote><p>Then just read the config with <strong>viper.ReadInConfig()</strong>, handle the error, and return a ViperConfig.</p><p><strong>ViperConfig</strong> have two <a href="https://go.dev/tour/methods/4">receiver methods</a> <strong>GetServerConfig()</strong> and <strong>GetConfig()</strong>, that return <strong>ServerConfig</strong> and <strong>Config</strong> respectively <strong>same like Config interface in config.go</strong>. So… ViperConfig implicitly implemented Config because ViperConfig implemented Config interface methods. <a href="https://go.dev/tour/methods/10"><strong>Implicit implementation power!</strong></a></p><p>Now we can use our config implementation; let&#39;s go to the main file and add an update.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c8c42b73853bcc1a76c520f2fefb708/href">https://medium.com/media/2c8c42b73853bcc1a76c520f2fefb708/href</a></iframe><p>And then run.</p><pre>$ make run</pre><p>If you see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qV57lQAl03a7NamLsYLIA.png" /></figure><p>It is because all work fine. Config implementation works!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6ozomjwcQJpdz5p6%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fsiliconvalleyhbo-3o6ozomjwcQJpdz5p6&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2F3o6ozomjwcQJpdz5p6%2Fgiphy.gif%3Fcid%3D790b7611982611adde1b7918425697a4d875c8e29fee6133%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/da4d7a9ece8c37ea7e6c0f00bbfe604b/href">https://medium.com/media/da4d7a9ece8c37ea7e6c0f00bbfe604b/href</a></iframe><h3>Conclusion</h3><p>This article taught us how to use Buf to manage the protobuffer code generation workflow easily and create a Makefile to automatize some development jobs like generate, run, clean, and build.</p><p>Also, we see how to start a gRPC server, abstract the configuration struct, and implement it with Viper! so we can read any config files like .env, .json, or .yaml.</p><p>In case you didn’t notice, we created a good folder structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*1RaEYv1zI_7rKDdv20RVhQ.png" /><figcaption>Project folder structure</figcaption></figure><p>In the future article, I will explain the detail of these folders, but if you don&#39;t want to wait, <a href="https://github.com/golang-standards/project-layout">here is the Go project layout standard documentation.</a></p><p>I hope this article helps you in learning about Go. Please comment and share if you think it is helpful 😉</p><p>Repository: <a href="https://github.com/lukas-andre/go-grpc-login/tree/protobuf-config-init-server">https://github.com/lukas-andre/go-grpc-login/tree/protobuf-config-init-server</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f015d7d4ac7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>