<?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 Jan Stamer on Medium]]></title>
        <description><![CDATA[Stories by Jan Stamer on Medium]]></description>
        <link>https://medium.com/@remast?source=rss-acf3168ed19a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MEY2dQen0-THyI59vTmG5A.jpeg</url>
            <title>Stories by Jan Stamer on Medium</title>
            <link>https://medium.com/@remast?source=rss-acf3168ed19a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:28:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@remast/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 Integration Tests using Testcontainers]]></title>
            <link>https://medium.com/@remast/go-integration-tests-using-testcontainers-8877e4b1c811?source=rss-acf3168ed19a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8877e4b1c811</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Jan Stamer]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 15:53:15 GMT</pubDate>
            <atom:updated>2024-08-07T06:14:37.371Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3iJoydthT7HhFOEu8-tgw.jpeg" /></figure><p>Your application uses a database like Postgres? So how do you test your persistence layer to ensure it’s working properly with a real <a href="https://www.postgresql.org/">Postgres</a> database? Right, you need to test against a real <a href="https://www.postgresql.org/">Postgres</a>. Since that test requires external infrastructure it’s an <em>integration test</em>. You’ll learn how easy it is to write integration tests for your <a href="https://go.dev/">Go</a> application using <a href="https://golang.testcontainers.org/">Testcontainers</a> and <a href="https://www.docker.com/">Docker</a>.</p><h3>Integration Test Setup</h3><p>Our application stores users in a <a href="https://www.postgresql.org/">Postgres</a> database. It uses the struct <em>UserRepository</em> with a method <em>FindByUsername</em> that uses plain SQL to find a user by username. We will write an integration test running against a real <a href="https://www.postgresql.org/">Postgres</a> in <a href="https://www.docker.com/">Docker</a> for the method <em>FindByUsername</em>.</p><p>The integration test for the <em>FindByUsername</em> of our <em>UserRepository</em> looks like:</p><pre>func TestUserRepository(t *testing.T) {<br> // 1. Setup database<br> dbContainer, connPool := SetupTestDatabase()<br> defer dbContainer.Terminate(context.Background())<br><br> // 2. Create user repository<br> repository := NewUserRepository(connPool)<br><br> // 3. Run tests against db<br> t.Run(“FindExistingUserByUsername”, func(t *testing.T) {<br>   adminUser, err := repository.FindByUsername(<br>     context.Background(),<br>     “admin”,<br>   )<br><br>   is.NoErr(err)<br>   is.Equal(adminUser.Username, “admin”)<br> })<br>}</pre><p>First the database is set up. Then a new <em>UserRepository</em> is created for the test with a reference to the connection pool of the database <em>connPool</em>. No we run the method to test <em>userRepository.FindByUsername(ctx, “admin”)</em> and verify the result. But wait, where did that database container come from? Right, we’ll set that up using <a href="https://golang.testcontainers.org/">Testcontainers</a> and <a href="https://www.docker.com/">Docker</a>.</p><h3>Database Setup using Testcontainers</h3><p>We set up the <a href="https://www.postgresql.org/">PostgreSQL</a> database in a <a href="https://www.docker.com/">Docker</a> container using the <a href="https://golang.testcontainers.org/">Golang Testcontainers</a> library.</p><p>As a first step we create a <em>testcontainers.ContainerRequest</em> where we set the Docker image to <em>postgres:16-alpine</em> with exposed port <em>5432/tcp</em>. The database name as well as username and password are set using environment variables. And to make sure the test only starts when the database container is up and running we wait for it using the <em>WaitingFor</em> option with <em>wait.ForListeningPort(“5432/tcp”)</em>.</p><p>Now as second step we start the requested container.</p><p>Finally in step 3 we use host and port of the running database container in the connection string for the database with <em>fmt.Sprintf(“postgres://postgres:postgres@%v:%v/testdb”, host, port.Port())</em>. Now we connect with <em>pgxpool.New(context.Background(), dbURI)</em>.</p><p>The whole method <em>SetupTestDatabase</em> to set up the PostgreSQL container is (errors omitted):</p><pre>func SetupTestDatabase() (testcontainers.Container, *pgxpool.Pool) {<br> // 1. Create PostgreSQL container request<br> containerReq := testcontainers.ContainerRequest{<br>  Image:        &quot;postgres:16-alpine&quot;,<br>  ExposedPorts: []string{&quot;5432/tcp&quot;},<br>  WaitingFor:   wait.ForListeningPort(&quot;5432/tcp&quot;),<br>  Env: map[string]string{<br>   &quot;POSTGRES_DB&quot;:       &quot;testdb&quot;,<br>   &quot;POSTGRES_PASSWORD&quot;: &quot;postgres&quot;,<br>   &quot;POSTGRES_USER&quot;:     &quot;postgres&quot;,<br>  },<br> }<br><br> // 2. Start PostgreSQL container<br> dbContainer, _ := testcontainers.GenericContainer(<br>  context.Background(),<br>  testcontainers.GenericContainerRequest{<br>   ContainerRequest: containerReq,<br>   Started:          true,<br>  })<br><br> // 3.1 Get host and port of PostgreSQL container<br> host, _ := dbContainer.Host(context.Background())<br> port, _ := dbContainer.MappedPort(context.Background(), &quot;5432&quot;)<br><br> // 3.2 Create db connection string and connect<br> dbURI := fmt.Sprintf(&quot;postgres://postgres:postgres@%v:%v/testdb&quot;, host, port.Port())<br> connPool, _ := pgxpool.New(context.Background(), dbURI)<br><br> return dbContainer, connPool<br>}</pre><p>Notice that we make sure the PostgreSQL container is terminated after our integration tests with <em>defer dbContainer.Terminate(context.Background())</em>.</p><h3>Adding Database Migrations</h3><p>So far our test starts out with an empty database. That’s not very useful since we need the database tables of our application. In our example we need the table <em>users</em>. We will now set up our database using <a href="https://github.com/golang-migrate/migrate">golang-migrate</a>.</p><p>We add the database migrations to the <em>SetupTestDatabase()</em> method by adding the call <em>MigrateDb(dbURI)</em>.</p><pre>func SetupTestDatabase() (testcontainers.Container, *pgxpool.Pool) {<br> // … (see before)<br> <br> // 3.2 Create db connection string and connect<br> dbURI := fmt.Sprintf(“postgres://postgres:postgres@%v:%v/testdb”, host, port.Port())<br> MigrateDb(dbURI)<br> connPool, _ := pgxpool.Connect(context.Background(), dbURI)<br><br> return dbContainer, connPool<br>}</pre><p>The method <em>MigrateDb(dbURI)</em> applies the database migrations to the database using <a href="https://github.com/golang-migrate/migrate">golang-migrate</a>. The migration scripts are read from the directory <em>migrations</em> which is embedded into the binary of our application.</p><pre>//go:embed migrations<br>var migrations embed.FS<br><br>func MigrateDb(dbURI string) error {<br> source, _ := iofs.New(migrations, “migrations”)<br><br> m, _ := migrate.NewWithSourceInstance(“iofs”, source, strings.Replace(dbURI, “postgres://”, “pgx5://”, 1))<br> defer m.Close()<br><br> err = m.Up()<br> if err != nil &amp;&amp; !errors.Is(err, migrate.ErrNoChange) {<br>   return err<br> }<br> <br> return nil<br>}</pre><h3>Wrap Up</h3><p>We have a working setup for integration tests against a real <a href="https://www.postgresql.org/">Postgres</a> database running in <a href="https://www.docker.com/">Docker</a> using <a href="https://golang.testcontainers.org/">Testcontainers</a>. We can use this setup for integration tests of our persistence layer. But that’s not all it’s good for.</p><p>This setup is great for all kinds of integration tests that need infrastructure. E.g. a test that send emails to an mail server running in docker, as in <a href="https://github.com/Baralga/baralga-app/blob/main/shared/mail_resource_smtp_test.go">mail_resource_smtp_test.go</a>.</p><p>Check out the sample code at <a href="https://github.com/remast/go-for-testcontainers">github.com/remast/go-for-testcontainers</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8877e4b1c811" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The DDD Hamburger for Go]]></title>
            <link>https://medium.com/@remast/the-ddd-hamburger-for-go-61dba99c4aaf?source=rss-acf3168ed19a------2</link>
            <guid isPermaLink="false">https://medium.com/p/61dba99c4aaf</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Jan Stamer]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 19:02:12 GMT</pubDate>
            <atom:updated>2024-01-08T12:59:35.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*4rDVdbLx1UoqjcsYJj1ZuQ.png" /></figure><p>The DDD Hamburger is my favorite type of architecture for <a href="https://go.dev/">Go</a>. Why? The DDD Hamburger beautifully combines the best of the <a href="https://alistair.cockburn.us/hexagonal-architecture/">hexagonal architecture</a> of <a href="https://martinfowler.com/bliki/DomainDrivenDesign.html">Domain-Driven-Design</a> and layered architecture.</p><p>Get to know the DDD Hamburger Architecture for Go and maybe it’ll become your favorite too!</p><h3><strong>The DDD Hamburger Overview 🍔</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*CCAzJUkV-kYuK4L7_aa66Q.png" /><figcaption>DDD Hamburger Overview</figcaption></figure><p>The DDD Hamburger is a real Hamburger with well defined layers from top to bottom:</p><p><strong>The upper Bun half</strong> 🍞<br>The upper bun half is the top of the Hamburger and is the <em>presentation layer</em>. The presentation layer contains your REST API and the web interface.</p><p><strong>The Salad</strong> 🥗<br>Below the bun is the salad which is the <em>application layer</em>. The application layer contains the use case logic of your application.</p><p><strong>The Meat</strong> 🥩<br>Next is the meat of your Hamburger, the <em>domain layer</em>. Just like the meat the domain layer is the most important part of your Hamburger. The domain layer contains you domain logic and all entities, aggregates and value objects of your domain.</p><p><strong>The lower Bun half</strong> 🍞<br>The lower bun half is the <em>infrastructure layer</em>. The infrastructure layer contains concrete implementations of your repositories for a Postgres database. The infrastructure layer implements interfaces declared in the domain layer.</p><p>Got the idea? Great, so let’s look into the details.</p><h3><strong>Go Example of the DDD Hamburger</strong></h3><p>Now we’ll code a Go application using our DDD Hamburger. We’ll use a simple time tracking example application with activities to show the practical Go implementation. New activities are added using a REST API and are then stored in a Postgres database.</p><p>The DDD Hamburger Architecture applied to Go is shown below. We’ll go through all layers of the Hamburger in detail soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*ayyPxR1lLrv4US4qYPlFbw.png" /></figure><h3><strong>The Presentation Layer as Upper Bun 🍞</strong></h3><p>The presentation layer contains the HTTP handlers for the REST API. The HTTP handlers like <em>HandleCreateActivity</em> create simple handler functions. All handlers for activities hang off a single struct <em>ActivityRestHandlers</em>, as the code below shows.</p><pre>type ActivityRestHandlers struct {<br> actitivityService  *ActitivityService<br>}<br><br>func (a ActivityRestHandlers) HandleCreateActivity() http.HandlerFunc {<br> return func(w http.ResponseWriter, r *http.Request) {<br>        // ...<br> }<br>}</pre><p>The actual logic to create a new activity is handled by a service <em>ActivityService</em> of the underlying application layer.</p><p>The HTTP handlers don’t use the activity entity of the domain layer as JSON representation. They use their own model for JSON which contains the struct tags to serialize it to JSON properly, as you see below.</p><pre>type activityModel struct {<br> ID          string        `json:&quot;id&quot;`<br> Start       string        `json:&quot;start&quot;`<br> End         string        `json:&quot;end&quot;`<br> Duration    durationModel `json:&quot;duration&quot;`<br>}</pre><p>That way our presentation layer only depends on the application layer and the domain layer, not more. We allow relaxed layers, which means it’s ok to skip the application layer and use stuff from the domain layer directly.</p><h3><strong>The Application Layer as Salad 🥗</strong></h3><p>The application layer contains services which implement the use cases of our application. One use case is to create an activity. This use case is implemented in the method <em>CreateActivity</em> that hangs of the application service struct <em>ActitivityService</em>.</p><pre>type ActitivityService struct {<br> repository ActivityRepository<br>}<br><br>func (a ActitivityService) CreateActivity(ctx context.Context, activity *Activity) (*Activity, error) {<br> savedActivity, err := a.repository.InsertActivity(ctx, activity)<br>    // ... do more<br> return savedActivity, nil<br>}</pre><p>The application service uses the repository interface <em>ActivityRepository</em> for the use case. Yet it only knows the interface of the repository which is declared in the domain layer. The actual implementation of that interface is not of concern to the application layer.</p><p>The application services also handle the transaction boundaries, since one use case shall be handled in one single atomic transaction. E.g. the use case of creating an new project with an initial activity for it has to go through in one transaction although it’ll use one repository for activities and one for projects.</p><h3><strong>The Domain Layer as Meat 🥩</strong></h3><p>The most important part is the domain layer which is the meat of our DDD hamburger. The domain layer contains the domain entity <em>Activity</em>, the logic of the domain like calculating the activity’s duration and the interface of the activity repository.</p><pre>// Activity Entity<br>type Activity struct {<br> ID             uuid.UUID<br> Start          time.Time<br> End            time.Time<br> Description    string<br> ProjectID      uuid.UUID<br>}<br><br>// -- Domain Logic<br>// DurationDecimal is the activity duration as decimal (e.g. 0.75)<br>func (a *Activity) DurationDecimal() float64 {<br> return a.duration().Minutes() / 60.0<br>}<br><br>// ActivityRepository<br>type ActivityRepository interface {<br> InsertActivity(ctx context.Context, activity *Activity) (*Activity, error)<br>    // ... lot&#39;s more<br>}</pre><p>The domain layer is the only layer that’s not allowed to depend on other layers. It should also be implemented using mostly the Go standard library. That’s why we neither use struct tags for json nor any database access code.</p><h3><strong>The Infrastructure Layer as Lower Bun 🍞</strong></h3><p>The infrastructure layer contains the concrete implementation of the repository domain interface <em>ActivityRepository</em> in the struct <em>DbActivityRepository</em>. This repository implementation uses the Postgres driver <a href="https://github.com/jackc/pgx">pgx</a> and plain SQL to store the activity in the database. It uses the database transaction from the context, since the transaction was initiated by the application service.</p><pre>// DbActivityRepository is a repository for a SQL database<br>type DbActivityRepository struct {<br> connPool *pgxpool.Pool<br>}<br><br>func (r *DbActivityRepository) InsertActivity(ctx context.Context, activity *Activity) (*Activity, error) {<br> tx := ctx.Value(shared.ContextKeyTx).(pgx.Tx)<br> _, err := tx.Exec(<br>  ctx,<br>  `INSERT INTO activities <br>     (activity_id, start_time, end_time, description, project_id) <br>   VALUES <br>     ($1, $2, $3, $4, $5)`,<br>  activity.ID,<br>  activity.Start,<br>  activity.End,<br>  activity.Description,<br>  activity.ProjectID,<br> )<br> if err != nil {<br>  return nil, err<br> }<br> return activity, nil<br>}</pre><p>The infrastructure layer depends on the domain layer and may use all entities, aggregates and repository interfaces from the domain layer. But from the domain layer only.</p><h3><strong>Assemble the Burger in the Main Function</strong></h3><p>No we have meat, salad and bun lying before us as single pieces. It’s time to make a proper Hamburger out of these pieces. We assemble our Hamburger in the main function, as you see below.</p><p>To wire the dependencies correctly together we work from bottom to top:</p><ol><li>First we create a new instance of of the db activity repository <em>DbActivityRepository</em> and pass in the database connection pool.</li><li>Next we create the application service <em>ActivityService</em> and pass in the repository.</li><li>Now we create the <em>ActivityRestHandlers</em> and pass in the application services. We now register the HTTP handler functions with the HTTP router.</li></ol><p>The code to assemble our DDD Hamburger architecture is like this:</p><pre>func main() {<br>    // ...<br><br>    // Infrastructure Layer with concrete repository<br> repository := tracking.NewDbActivityRepository(connectionPool)<br><br>    // Application Layer with service<br>    appService := tracking.NewActivityService(repository)<br> <br>    // Presentation Layer with handlers<br>    restHandlers := tracking.NewActivityRestHandlers(appService)<br>    router.HandleFunc(&quot;/api/activity&quot;, restHandlers.HandleCreateActivity())<br>}</pre><p>The code to assemble our Hamburger is plain, simple and very easy to understand. I like that, and it’s all I usually need.</p><h3><strong>Package Structure for the DDD Hamburger</strong></h3><p>One question remains: Which structure of our Go packages is best suited for the DDD Hamburger?</p><p>I usually start out with a single package for all layers. So a single package <em>tracking</em> with files <em>activity_rest.go</em> for the rest handlers, <em>activity_service.go</em> for application services, the domain layer in <em>activity_domain.go</em> and the database repository in <em>activity_repository_db.go</em>.</p><p>A next step is to separate out all layers as separate packages, except the domain layer. So we’d have a root package <em>tracking</em>. The root package contains the domain layer. The root package has sub package for each layer like <em>application</em>, <em>infrastructure</em>, <em>presentation</em>. Why the domain layer in the root package? That way we can use the domain layer with it’s proper name. So if we’d use the domain entity <em>Activity</em> somewhere, the code would read <em>tracking.Activity</em> which is very nice to read.</p><p>Whichever package structure is best depends on your project. I’d suggest you start small and easy and adjust it as your project grows over time.</p><h3><strong>Wrap Up of the DDD Hamburger 🍔</strong></h3><p>The DDD Hamburger is a layered architecture based fully on Domain Driven Design. It’s very easy to understand and follow. That’s why the DDD Hamburger is my favorite architectural style. In general and especially in Go.</p><p>Using the DDD Hamburger for your Go application is pretty straightforward, as you’ve seen. You can start out small yet you’re able to grow as needed.</p><p>See an application of the DDD Hamburger at <a href="https://github.com/Baralga/baralga-app">baralga-app</a>.</p><h3><strong>Credits</strong></h3><p>The DDD Hamburger Architecture was coined by <a href="https://www.wps.de/wps/team/henning-schwentner">Henning Schwentner</a>, so thanks for that. Another great influence for structuring the HTTP handlers came from <a href="https://pace.dev/blog/2018/05/09/how-I-write-http-services-after-eight-years.html">Mat Ryer</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61dba99c4aaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplest WebServer for Angular in 6 Lines]]></title>
            <link>https://medium.com/@remast/simplest-webserver-for-angular-in-6-lines-e8dc12eddd42?source=rss-acf3168ed19a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8dc12eddd42</guid>
            <category><![CDATA[caddy-server]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jan Stamer]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 13:19:53 GMT</pubDate>
            <atom:updated>2024-01-09T08:44:09.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mCLPLBahb-wEuaVm" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How do you serve your <a href="https://angular.io/">Angular</a> app? Learn to build a web server for your <a href="https://angular.io/">Angular</a> app in 6 lines of code. Throw in 8 more lines and you have a multi stage <a href="https://www.docker.com/">Docker</a> build for your web server along with it.</p><h3>Angular Web Server in 6 Lines</h3><p>6 lines of code, that’s all it takes for a simple <a href="https://angular.io/">Angular</a> WebServer powered by <a href="https://caddyserver.com/">Caddy</a>:</p><pre>:4200 {<br> root * /usr/share/caddy<br> encode gzip<br> try_files {path} /index.html<br> file_server<br>}</pre><h3>Multi Stage Docker Build in 8 Lines</h3><p>Now let’s throw in another 8 lines of code to get a multi stage <a href="https://www.docker.com/">Docker</a> build for our Angular frontend.</p><p>As a result you’ll get a <a href="https://caddyserver.com/">Caddy</a> powered container of your Angular app.</p><pre># 1. Frontend Builder<br>FROM node:18 as builder<br>WORKDIR /app<br>ADD . /app<br>RUN npm ci &amp;&amp; npm run build<br><br># 2. Frontend Container<br>FROM caddy:2.6.4-alpine<br>EXPOSE 4200<br>COPY Caddyfile /etc/caddy/Caddyfile<br>COPY --from=builder /app/dist/frontend/* /usr/share/caddy</pre><p>Check it out live and working in our <a href="https://github.com/crossnative/cloudland-rps/tree/main/frontend">Github repo (folder frontend)</a>. Have fun and enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8dc12eddd42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go for SonarQube]]></title>
            <link>https://medium.com/@remast/go-for-sonarqube-ffff5b74f33a?source=rss-acf3168ed19a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffff5b74f33a</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[sonarqube]]></category>
            <dc:creator><![CDATA[Jan Stamer]]></dc:creator>
            <pubDate>Mon, 11 Feb 2019 07:11:09 GMT</pubDate>
            <atom:updated>2023-07-28T07:36:41.570Z</atom:updated>
            <content:encoded><![CDATA[<p>Static code analysis is a great and easy way to discover bugs, race conditions, code smells or to check whether code matches the coding conventions. I will motivate why it’s useful to use SonarQube for static analysis of Go code and show you how it’s done.</p><h3>Go Vet</h3><p>Go already ships with the tool <em>vet</em> which does static code analysis of Go code. To use <em>vet</em> just run go vet source/directory/*.go. Vet will perform various checks like detecting shadowed variables, nil function comparison and many others (see go doc cmd/vet for a full list) and list all violations. Vet is great because it performs many basic checks very fast.</p><h3>Go Linters</h3><p>Yet if we want to detect style mistakes, duplicated code or even check for security problems go vet is not enough. All these checks can be done by linters like <a href="https://github.com/alecthomas/gometalinter">Go Meta Linter</a> or <a href="https://github.com/golangci/golangci-lint">GolangCI-Lint</a>. These are <a href="https://en.wikipedia.org/wiki/Lint_(software)">classic linters</a> that perform static code analysis on go code and report their results in a standardized format. These linters can be integrated in editors like <a href="https://code.visualstudio.com/">VisualStudio Code</a>, <a href="https://www.vim.org/">Vim</a> or <a href="https://www.jetbrains.com/go/">GoLand</a>. So, these linters perform in-depth analysis of Go code and can detect many kinds of violations. Depending on the linter configuration the linting can take a significant time in your build pipeline.</p><p>Static code analysis is also useful to calculate key metrics of your source code like lines of code or cyclomatic complexity. Combined with code coverage or unit test count these key metrics can provide a good first impression on the state of your source code. They can be displayed on a dashboard like <a href="https://bitbucket.org/atlassian/atlasboard">atlasboard</a> in your project for all to see.</p><p>But where do we get these key metrics from? Linters like Go Meta Linter can calculate most of the key metrics like<a href="https://en.wikipedia.org/wiki/Cyclomatic_complexity"> cyclometric complexity</a>. Other key metrics like code coverage of unit test count are calculated from the tests. That way we can calculate the key metrics during the continuous integration pipeline.</p><h3>Are Linters not enough? Why SonarQube?</h3><p>What if we want to know how the key metrics of our source code evolved over time? Have we been able to improve code coverage since the last release? How many lines of code do we add each sprint? Which components in our projects are the biggest?</p><p>That’s where <a href="https://www.sonarqube.org/">SonarQube</a> comes into play. SonarQube analyzes source code using static code analysis, code coverage and unit tests over time. That way SonarQube is able to answer all the questions above. You see that version 1.0.0 had 1.562 lines of code with a coverage of 85%, whereas now you are at version 2.1.0 with 3.842 lines of code. If you look closer, you see that the package <em>auth</em> has grown the most. In SonarQube you see how your key metrics and your source code have evolved over time and over specific versions like shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*1WghVIB-dXfVpXTZ.png" /><figcaption><em>SonarQube results over time</em></figcaption></figure><p>If you have a project or a company developing services in different programming languages, you have another benefit of using SonarQube for key source code metrics. SonarQube is able to calculate these key metrics for many different programming languages like Go, Java, C#, JavaScript and many others. That way you can calculate combined key metrics even for projects or companies which use many different programming languages. E.g. you your project overall has 12.346 lines of code with an overall code coverage of 76%. The JavaScript frontend has 3.704 lines of code which is round about one third of your Java backend.</p><p>Let’s see how we can analyze our Go code using SonarQube.</p><h3>SonarQube for Go</h3><p>To analyze Go code with SonarQube you need a running SonarQube. You can run SonarQube locally with <em>docker run — name sonarqube -p 9000:9000 sonarqube</em>. The Go plugin comes with SonarQube so no need to install it manually. Now you are ready to analyze your source code. For that we use the <a href="https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner">sonar-scanner tool</a> provided by SonarQube, which needs a Java Runtime Environment. Next we need a configuration file for SonarQube named <em>sonar-project.properties</em> in the root of your project. The configuration file tells SonarQube which sources to analyze, the name and version of the project and where to find the test coverage. See an example <em>sonar-project.properties</em> below:</p><pre>sonar.projectKey=de.red6:service_sonar<br>sonar.projectName=service_sonar<br>sonar.projectVersion=1.0.0<br>sonar.host.url=http://localhost:9000<br>sonar.login=**SECRET**<br><br>sonar.sources=.<br>sonar.exclusions=**/*_test.go,**/vendor/**,**/testdata/*<br><br>sonar.tests=.<br>sonar.test.inclusions=**/*_test.go<br>sonar.test.exclusions=**/vendor/**<br>sonar.go.coverage.reportPaths=bin/cov.out</pre><p>Before you can analyze your code with SonarQube you need to run the tests and record the code coverage (e.g. with go test -short -coverprofile=bin/cov.out `go list./..|grep -v vendor/`). SonarQube will use the recorded code coverage.</p><p>Now you can run your first SonarQube analysis using <em>sonar-scanner</em>. Your code will be analyzed and uploaded to SonarQube including the code coverage.</p><h3>Example</h3><p>You find a sample project <a href="https://github.com/remast/service_sonar">service_sonar</a> with the full setup for SonarQube. In the sample project you can run the SonarQube analysis with make sonar. If you don’t have the <em>sonar-scanner</em> tool installed on your machine you can also use a dockerized version of the sonar scanner (see <a href="https://github.com/remast/service_sonar/blob/master/README.md">sample project</a>). The dockerized version is a great fit for CI environments like <a href="https://about.gitlab.com/product/continuous-integration/">GitlabCI</a>.</p><p>All settings in the configuration file <em>sonar-project.properties</em> can also be provided using the command line. This makes sense especially for the SonarQube host and login. So in you CI pipeline you can run sonar-scanner-Dsonar.host.url=&quot;http://sonar.mycompany.com&quot; -Dsonar.login=&quot;**MY_TOKEN**&quot;.</p><p>The sample project also includes a configuration for Gitlab CI in <em>.gitlab-ci.yml</em>. The Gitlab CI pipeline performs a SonarQube analysis in the stage sonar. It expects the host and login for SonarQube in the environment variables SONAR_HOST and SONAR_API_TOKEN.</p><p>After running the SonarQube analysis you see the results in SonarQube:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*-GrR0ztWw5Yso5C5.png" /><figcaption><em>Result of first SonarQube analysis</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*W_5H1cXY5lS-aa8q.png" /><figcaption><em>Overview of SonarQube results</em></figcaption></figure><h3>Summary</h3><p>We have learned how to statically analyze Go code using the build in tool <em>vet</em>, linters like Go Meta Lint or the SonarQube plugin for Go. All of these tools are capable of calculating key metrics of your source code.</p><p>SonarQube provides two benefits:</p><ul><li>First it can track changes of your key metrics over time and by that provide useful insights on how your code quality is evolving.</li><li>Second SonarQube can analyze code in many different programming languages and so you can calculate overall key metrics.</li></ul><p>So you should definitely give <a href="https://www.sonarqube.org/">SonarQube</a> for Go a try.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffff5b74f33a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>