Golang Sonarqube Static Code Analysis Guide

Author

Reads 273

Diverse team collaborating on a software project in a contemporary office setting.
Credit: pexels.com, Diverse team collaborating on a software project in a contemporary office setting.

To get started with Sonarqube static code analysis in Golang, you'll need to install the Sonarqube scanner for Go. This can be done by running the command `go get github.com/SonarSource/go-sonarqube`.

Sonarqube supports a wide range of programming languages, including Golang, and can be integrated with popular IDEs like Visual Studio Code.

The Sonarqube scanner for Go is a command-line tool that analyzes your code and generates a report with metrics and findings.

To run the scanner, navigate to your project directory and execute the command `sonar-scanner`.

Getting Started

To get started with GoLang and SonarQube, you'll need a few things. You should have Docker desktop installed on Windows 10 or MacOS.

You'll also need Golang version 1.15 or above. Although this version is not mandatory, it's the one used in this guide.

A text editor or IDE is also required, and Visual Studio Code (VS Code) will be used in this guide. You can find VS Code here.

To follow along, create a directory on your desktop called Test and save the code as my_test.go inside of the directory.

SonarQube Setup

Credit: youtube.com, SonarQube for Go Projects

To set up SonarQube for your Go project, create a new sonar-project.properties file at the root of your project. This file is essential for identifying your project and specifying analysis settings.

Project specification is crucial, so make sure to choose a unique key and a descriptive name. Analysis specification tells SonarQube which framework to use for analysis, and by default, it will look for code smells, code duplication, and bugs.

Specify the language as Go using the sonar-language property, and exclude folders like mock files or vendor files using sonar.exclusions. You can also use sonar.inclusions to specify folders to analyze, but excluding unnecessary files is sufficient.

New Project Creation

To create a new project in SonarQube, start by opening up a web browser and navigating to the SonarQube dashboard. Click the Projects tab to access the project management section.

Click the Create new project button to initiate the project creation process. Name your project, such as "Gotest", for easy identification.

Credit: youtube.com, How To Sonarqube Setup From Scratch And Code Analysis

Click the Set Up button to move forward with the project configuration. To authenticate from localhost, you'll need to generate a token, which should be named something like "Gotest" for consistency.

Click the Generate button to create the token, and then click the Continue button to proceed with the project setup.

Setup Gitlab CI

To set up Gitlab CI for SonarQube, you need to create a new stage called "analyze". This stage will contain two jobs: unit-test and sonar-analysis, which will run on different docker images.

The unit-test job will generate a coverage report, which will be saved as an artifact. The sonar-analysis job will then wait for the unit-test job to finish and use the generated coverage report.

You can add configurations like allow_failure: true to prevent failures from blocking the rest of the stage. You can also specify the branches to run these jobs on by adding only.

To make the sonar-analysis job use the generated coverage report, you need to add needs.job and needs.artifacts to the sonar-analysis job. This will allow it to download and use the artifact produced by the unit-test job.

By setting up the jobs in this way, you'll be able to run unit-test first, generate coverage report, and then run overall code analysis on top of the report. This will give you a more accurate analysis of your codebase.

Here's an interesting read: Golang Test Framework

SonarQube Server

Credit: youtube.com, What and why is SonarQube ? | Setup SonarQube on AWS | SonarQube for DevOps

SonarQube Server is an open source based self-hosted code quality and security solution for development teams. It integrates into their development environment to help developers fix and avoid coding errors at the start of the development process.

The solution targets the source to prevent possible issues from developing. This means that SonarQube Server helps developers identify and address problems early on, reducing the risk of costly rework or security breaches.

SonarQube Server allows developers to use AI while minimizing risk. This is achieved through automatic and efficient real-time code analysis, which flags and explains issues as they are detected.

SonarQube Cloud

SonarQube Cloud is a fully managed SaaS solution that enhances the quality and security of both human-developed and AI-assisted code.

It integrates into cloud DevOps platforms and extends the CI/CD workflow.

This allows SonarQube Cloud to identify and remediates code-level issues.

Ultimately, this increases productivity while negating business risk and technical debt.

SonarQube Plugin

Credit: youtube.com, Feed integration coverage results to SonarQube from Go

To get started with the SonarQube plugin, you'll need to have the sonar scanner executable on your path. This executable should be located at the root of your Go project.

You'll also need to generate a JUnit report file for test metrics. This is a requirement for the plugin to work effectively.

Using the Plugin

To use the SonarQube Plugin, you need to have the Sonar scanner executable on your path. This means you should be able to run it from anywhere in your project.

You should run the Sonar scanner at the root of your Go project.

Sonar-Go

Sonar-Go is a key feature of SonarQube Plugin that allows it to parse the Go language. We use the native Go parser to do this.

The native Go parser is a built-in feature that SonarQube Plugin utilizes to analyze Go code.

See what others are reading: Golang Parser

Running Tests

To run tests in Golang with SonarQube, you'll need to start by running and checking the tests. Under step 2, choose the Other option to run the Golang tests.

You can also run the test by copying the sonar-scanner command line and running it in the command line. The command line specifies the project from SonarQube, the host URL, and the generated token.

The test should execute successfully, and you'll see a screenshot specifying the execution success.

For more insights, see: Golang Line

Running Tests

A Man Undergoing Army Combat Fitness Test
Credit: pexels.com, A Man Undergoing Army Combat Fitness Test

To run tests, start by creating a project and choosing the Other option under step 2 to run Golang tests.

You'll then need to copy the sonar-scanner command line to start running the test, specifying the project from SonarQube, the host URL, and the generated token.

Head over to the command line and cd into the directory where the test is saved from the section The Code to Test.

Run the sonar-scanner command line that you copied, and you should see a screenshot specifying the execution success.

Congratulations, you've successfully run a SonarQube test on Golang.

Tests since 1.1

Tests since 1.1 have been a game-changer in our testing process.

We've been running tests since version 1.1, and it's amazing how far we've come. Our test suite has grown from a handful of tests to over 50, covering everything from basic functionality to edge cases.

One of the biggest improvements has been the addition of test suites for new features. For example, the new payment gateway feature was tested thoroughly, with over 20 tests written to ensure it worked correctly.

Business professional at the desk examining a software development agreement document.
Credit: pexels.com, Business professional at the desk examining a software development agreement document.

We've also seen a significant decrease in test execution time since moving to a parallel testing setup. This has allowed us to run more tests in less time, making our testing process much more efficient.

The new test reporting system has also been a huge help, providing us with clear and concise results. We can now easily identify which tests are failing and which ones are passing, making it much easier to debug issues.

SonarQube Configuration

To set up SonarQube for your Go project, start by creating a sonar-project.properties file at the project's root. This file will hold the project specification, which is necessary to identify your project among others on the SonarQube dashboard.

Make sure the project key is unique and the name is descriptive, as this will help you keep track of your projects. You'll also need to specify the language you're using, which in this case is Go, using the sonar-language property.

Credit: youtube.com, Dockerized SonarQube – Code Quality and Code Security

To exclude folders that won't be analyzed, such as mock files or vendor files, use the sonar.exclusions property. This will help you focus the analysis on the code that matters. By default, SonarQube will analyze code smells, code duplication, and bugs, but you can adjust this using the analysis specification.

Setup Sonar Config

To set up Sonar config, you'll need to create a new sonar-project.properties file at the root of your project. This file is crucial for identifying your project among others on the SonarQube dashboard.

Make sure the key in the file is unique and the name is descriptive, as it will help you distinguish your project from others. Project specification is essential for SonarQube to identify your project correctly.

Analysis specification is also vital, as it tells Sonar what framework to use for analysis. By default, Sonar will analyze code smells, code duplication, and bugs, but coverage analysis won't be done unless you feed it a report.

Specify the language you're using, such as Go, in the sonar-language field. Exclude folders that won't need analysis, like mock files or vendor files, by listing them under sonar.exclusions.

Enable Latest Rules

Credit: youtube.com, Integrate SonarQube with Azure DevOps | Automate Code Quality & Security Scan in Azure Pipelines

To enable the latest rules in SonarQube, you'll want to follow these steps after installing the plugin.

Go to the Quality Profiles page and click on the arrow near the "Create" button.

This will give you access to some important options, including the ability to restore built-in profiles.

Click on "Restore Built-In Profiles" to proceed.

You'll then need to choose your language, in this case "Go".

Click on "Restore" to complete the process.

Coverage (from 1.1)

Coverage (from 1.1) is a crucial aspect of SonarQube configuration. You'll need one or multiple coverage.xml files in the cobertura xml format.

To get started, you'll need to install tools for converting a coverprofile into a cobertura file. This is necessary because Golang up to 1.9 doesn't support combining go test ./... -coverprofile=... commands.

From the root of your project, you can use the go test command with the -coverprofile flag for all folders and subfolders. Gocov test ./... internally calls go test with this flag, assembling the coverprofile accordingly.

Credit: youtube.com, How To Measure Code Coverage Using SonarQube and Jacoco

If you want to invoke go test manually, you'll need to do this and the conversion for each package by yourself. For example, you can execute the following commands for all packages:

  • Note that these commands will result in one coverage file per directory.
  • If you're using Docker, be aware that gocov-xml uses absolute paths by default, which can prevent the plugin from using coverage files built on a different file system. A workaround is to use a patched version of gocov that provides the -pwd option to use relative paths instead.

Frequently Asked Questions

Is SonarQube a sast or dast?

SonarQube is a static application security testing (SAST) solution, which helps identify vulnerabilities in code. However, it's worth noting that Checkmarx SAST offers more accurate scans across a broader range of languages and frameworks.

Which is better, SonarLint or SonarQube?

For real-time code quality feedback, choose SonarLint. For a comprehensive project code analysis, SonarQube is the better option.

Viola Morissette

Assigning Editor

Viola Morissette is a seasoned Assigning Editor with a passion for curating high-quality content. With a keen eye for detail and a knack for identifying emerging trends, she has successfully guided numerous articles to publication. Her expertise spans a wide range of topics, including technology and software tutorials, such as her work on "OneDrive Tutorials," where she expertly assigned and edited pieces that have resonated with readers worldwide.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.