Autoreload go code on code change

For developers, the ability to autoreload code upon any changes is nothing short of a game-changer. It not only streamlines the development process but also fosters an environment of continuous improvement and experimentation.

There are so many packages for languages such as JavaScript for such a behaviour, but I struggled to easily find a simple-to-use go version with an example.

And that’s where this post comes in, as a simple to-the-point example extracted from what I learnt while reading https://dev.to/jacobsngoodwin/full-stack-memory-app-01-setup-go-server-with-reload-in-docker-62n

We will be making use of https://github.com/cespare/reflex, which is a go package and small tool to watch a directory and rerun a command when certain files change. 

Read more

Automatic cobra command registration with fx

Cobra is a popular Go package for creating CLIs. It provides a lot of functionality for creating commands, subcommands, and flags. However, it can be tedious to manually register all of your commands.

fx is a Go package that provides a dependency injection framework. It can be used to automatically register your application components, including but not limited to Cobra commands.

In this blog post, I will show you how you can use fx to automatically register your Cobra commands.

This code was written 5 minutes ago, but works, and I imagine it could help folks bootstrap more complex CLIs rapidly.

The problem

When you create a Cobra command, you need to manually register it with the root command. This can be tedious, especially if you have a lot of commands.

For example, the following code registers a command called hello:

func NewHelloCmd() *cobra.Command {
  cmd := &cobra.Command{
    Use:   "hello",
    Short: "Say hello",
    Run: func(cmd *cobra.Command, args []string) {
      cmd.Println("Hello, world!")
    },
  }
  return cmd
}

func main() {
  rootCmd := &cobra.Command{
    Use:   "myapp",
    Short: "My application",
  }
  rootCmd.AddCommand(NewHelloCmd())
  rootCmd.Execute()
}Code language: Go (go)

Read more

A copy-paste go SQL mock for GORM

When it comes to writing robust and reliable tests for your Go applications, having a well-structured and efficient testing setup is crucial. One common challenge in testing Go applications is dealing with database interactions. To ensure that your code functions correctly, it’s essential to create a controlled environment for database operations during testing. In this blog post, we’ll explore how to create a mock GORM database for testing purposes, allowing you to isolate and verify your database interactions in a controlled manner.

Here is some copy-and-paste code (explained below) which should get you started.

import (
	"github.com/DATA-DOG/go-sqlmock"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func NewMockGORM() (GORM *gorm.DB, close func()) {
	db, mock, err := sqlmock.New()
	if err != nil {
		panic(err)
	}

	// GORM always runs this query, so mock it for all tests
	mock.ExpectQuery("SELECT VERSION()").WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow("5.7.0"))

	GORM, err = gorm.Open(mysql.New(mysql.Config{Conn: db}), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
	if err != nil {
		panic(err)
	}

	return GORM, func() { db.Close() }
}Code language: PHP (php)

The code block above defines a NewMockGORM function that sets up a mock GORM database instance for testing. Let’s break down what this code does and how it can be a valuable addition to your testing toolkit.

Setting up a Mock GORM Database

Read more

Simple Go defer code example

In Go, a defer statement will execute a function call just before the function it is called from returns.

I found that most of the examples of a Go defer call online seemed to do complicated things with numbers. So here is a nice simple example with just text output.

Example

You can run this code yourself in The Go Playground! You can also find a similar example in the Go Tour.

package main

import (
	"fmt"
)

func main() {
	// This will output first (in order)
	fmt.Println("One")
	
	// This will output last (before this function finishes)
	defer fmt.Println("Two")
	
	// This will be called before the above defer call "Two"
	secondary()
}


func secondary() {
	// This will output after Four (before this function finishes)
	defer fmt.Println("Three")
	
	// This will output (in order)
	fmt.Println("Four")
}

Code language: JavaScript (javascript)

Read more