JagaScript

Logo
1 min read

How I Start New Go Projects in Seconds

March 09, 2020
tags: go, golang, terminal, cli

For the past years, I’ve started using more and more golang as a scripting language, and since in the past we were forced to put code in the GOPATH it became a little cumbersome compared to just write a bash file in the current folder

Project goinit

goinit

So I created a go program called goinit to generate a new project in my GOPATH at ~/go/src/github.com/kandros/[project-name] and open it in my editor, so far it server me very well, every new experiment is just a couple keystroke away goinit my-app, I literally can see something in the console in less than 15 seconds

Using go mod

Since go 1.11 I’ve started using go modules and stopped using goinit, a couple days ago I decided to refactor it to handle creating projects outside GOPATH and decided to use an even simpler solution, a custom shell function

goinit() {
 mkdir -p ~/coding/$1
 cd ~/coding/$1
 cat <<-EOF > main.go
 package main

 import "fmt"

 func main() {
    fmt.Println("hello")
    }
 EOF

 go mod init github.com/kandros/$1
 code-insiders --new-window . --goto main.go
}

It works the same way as my previous script by running goinit new-project in the terminal it will create the folder ~/coding/new-project open the project in VScode and the file main.go

Make the function accessible globally

This function is stored in my ~/.zshrc file to be available in the terminal, Bash users can put it in their ~/.bash_profile

Sharing is caring

Blog by Jaga Santagostino.
Software consultant, polyglot developer, maker of things, lifelong learner.
ReactJS Milano & milano.dev organizer