Install and configure Visual Studio Code

Install Visual Studio Code

See https://code.visualstudio.com/docs/setup/mac

Configure Visual Studio Code

Start Visual Studio Code from the command line

I think this is the most important setting. If anything, this should be enabled.

  • Start Visual Studio Code
  • Open the Command Palette
    • On Mac
      • press Shift, Command, P
    • On Windows
      • press Shift, Control, P
  • Type shell command into the search box
  • Select the Shell Command: Install ‘code’ command in PATH from the list
  • Restart the terminal for the change to take effect
  • Type code in the terminal to start Visual Studio Code

Customize Visual Studio Code

The Visual Studio Code configuration settings are stored in a JSON file on your workstation. You can edit the file and after restart the settings take effect, or you can set the values in the user interface one-by-one.

To customize Visual Studio Code by editing the settings file

Open the settings.json file. The double quotes are important, as both paths contain spaces.

On Mac: “$HOME/Library/Application Support/Code/User/settings.json”

On Windows: “%APPDATA%\Code\User\settings.json”

My current configuration settings file looks like this:

{
    "editor.acceptSuggestionOnEnter": "off",
    "workbench.colorTheme": "Solarized Light",
    "files.insertFinalNewline": true,
    "workbench.startupEditor": "newUntitledFile",
    "editor.renderWhitespace": "none",
    "editor.wordSeparators": "`~!@#$%^&*()=+[{]}\\|;:'\",.<>/?",
    "go.formatTool": "goimports",
    "go.useLanguageServer": true,
    "workbench.colorCustomizations" : {
        "activityBar.activeBackground":"#95968888"
    },
    "editor.tabSize": 2,
    "mssql.connections": [
        {
            "server": "{{put-server-name-here}}",
            "database": "{{put-database-name-here}}",
            "user": "{{put-username-here}}",
            "password": ""
        }
    ],
    "workbench.editorAssociations": {
        "*.ipynb": "jupyter-notebook"
    },
    "notebook.cellToolbarLocation": {
        "default": "right",
        "jupyter-notebook": "left"
    },
    "redhat.telemetry.enabled": false,
    "editor.minimap.enabled": false,
    "go.toolsManagement.autoUpdate": true,
    "search.exclude": {
        "**/.terraform": true
    },
    "[yml]": {
        "editor.insertSpaces": true,
        "editor.tabSize": 2,
        "editor.autoIndent": "advanced"
        },
    "[yaml]": {
        "editor.insertSpaces": true,
        "editor.tabSize": 2,
        "editor.autoIndent": "advanced"
        }
}

To customize Visual Studio Code using the UI

  • Open the settings page with Command-, (comma)

or

  • Start Visual Studio Code
  • Open Preferences -> Settings

Only tab should accept the suggestion

To force Visual Studio Code to only insert the suggested word with the Tab key, and configure the Enter key to always insert a new line

  • On the settings tab search for tab
  • Set the Editor: Accept Suggestion On Enter to off

Adds “editor.acceptSuggestionOnEnter”: “off” to the setting.json file

Add trailing newline to every file
  • On the settings tab search for insert final newline
  • Check the Insert Final Newline checkbox

Adds “files.insertFinalNewline”: true, to the settings.json file

Select text with hyphen with double click

To select the entire textwithhyphen with double click

  • On the settings tab search for editor.wordSeparators
  • Delete (hyphen) from the separator characters

Adds “editor.wordSeparators”: “`~!@#$%^&*()=+[{]}\\|;:’\”,.<>/?” to the settings.json file.

Exclude libraries from search

When we search the source code it can take along time for Visual Studio Code to search through the libraries that only support our application. Exclude the known library folders. Most of them are already included, add the .terraform folder to the list.

  • On the settings tab search for search.exclude and click the Add Pattern button
  • Enter **/.terraform into the field and click the OK button

Adds

"search.exclude": {
        "**/.terraform": true
    }

to the settings.json file.

Insert 2 spaces into the .yml and .yaml files when we press the tab key, use tabs in Makefile

  • Open the extensions page with Shift-Command-X
  • Install the EditorConfig for VS Code plugin
  • Save this .editorconfig file in the root of your project files above all projects ( for example in the ~/Git directory)
[Makefile]
indent_style = tab

[*.yml]
indent_style = space
indent_size = 2
  • Restart Visual Studio Code

Another setting for yml files, (maybe not necessary if the EditorConfig plugin is installed)

  1. Start Visual Studio Code
  2. Open the Settings page with Command-,
  3. Enter yml into the search field and press enter, and click the Edit settings for yaml link
  4. Enter into the settings.json file
    ,
    "[yml]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 2,
    "editor.autoIndent": false
    },
    "[yaml]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 2,
    "editor.autoIndent": false
    }

     

Upgrade Bash on macOS

To be able to debug Bash scripts in Visual Studio Code on macOS, we need to upgrade Bash to at least version 4.0. Even the most modern macOS installs, a more than 15 year old, Bash version 3.2.57 from 2007!!!

bash –version

GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
Copyright (C) 2007 Free Software Foundation, Inc.

To upgrade Bash to the latest version follow the instructions by Daniel Weibel at https://itnext.io/upgrading-bash-on-macos-7138bd1066ba

IMPORTANT!!!
If you use iTerm (zshell) keep /bin/zsh as the last item in the /etc/shells file to make it the default shell when you open iTerm.

...
/usr/local/bin/bash
/bin/zsh

Useful extensions

  • EditorConfig for VS Code
  • GitLens — Git supercharged
  • Go ms-vscode.go
  • Terraform mauve.terraform
  • Bash Debug rogalmic.bash-debug

You must specify a region. You can also configure your region by running “aws configure”.

When we execute an AWS CLI command, we need to supply the AWS Region. If it is not specified, we get the error message:

You must specify a region. You can also configure your region by running “aws configure”.

We can add the region with the –region command line argument, or store it in the ~/.aws/config file.

The format of the ~/.aws/credentials file is

[default]
aws_access_key_id = …
aws_secret_access_key = …

[my-account]
aws_access_key_id = …
aws_secret_access_key = …

The format of the ~/.aws/config file is the following. Make sure to add the word “profile” within the square brackets for every profile you specified in the credentials file, except for the “default” one!!!

[default]
region = us-east-1
output = json

[profile my-account]
region = us-east-1
output = json

x509: certificate signed by unknown authority

I have built a Docker container with a Go application that used the Go AWS SDK. When my program tried to access an S3 bucket I got the error message

RequestError: send request failed
caused by: Get https://MY_BUCKET_NAME.s3.amazonaws.com: x509: certificate signed by unknown authority

To solve the problem I had to add the following line to the Dockerfile

On Ubuntu

RUN apt ca-certificates && rm -rf /var/cache/apk/*

On Alpine

RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk/* 

Docker for Windows cannot start: “Hardware assisted virtualization and data execution protection must be enabled in the BIOS”

To start Docker on Windows, Hyper-V and the Hypervisor has to be enabled on Windows.

  1. Start a PowerShell window as administrator
  2. Enable Hyper-V
    dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All
  3. Enable the Hypervisor
    bcdedit /set hypervisorlaunchtype auto
  4. Restart the computer

List the Active Directory groups the user is a member of

To list the Active Directory groups where the current user is a member, execute in the PowerShell window

(New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")).FindOne().GetDirectoryEntry().memberOf

To get the Active Directory groups for another user, replace THE_USER_NAME with the Active directory user name of the person.

(New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=THE_USER_NAME))")).FindOne().GetDirectoryEntry().memberOf

Debugging Go programs in Atom

To be able to debug Go programs in Atom, make sure the Go IDE is installed. See Install the Go IDE at Install and set up Go

To start debugging select the Debugger tab in the upper right corner of Atom

If you get the error message: The debugger is not attached, and when you click Attach debugger you get the error message: No debuggers installed, look for available debuggers on atom.io/packages

Check if the go-debug Atom package is installed

  • Open the Settings page from the File menu
  • Select Install on the left side
  • Search for go-debug
  • If the package is not installed, click the Install button

If you still get the same error message, download the go-delve package.

Visit https://github.com/derekparker/delve/tree/master/Documentation/installation for more info.

  • In the terminal window execute
    go get -u github.com/go-delve/delve/cmd/dlv
  • Restart Atom for the change to take effect.

 To debug your Go application

  • Click the Debugger tab in the upper right corner, and select the Debug config
  • To set a breakpoint, click the line in the program and press the F9 key. A red circle appears on the margin. 
  • The breakpoint appears on the right side of the screen too
  • Press F5 to run the application in the debugger
  • When the breakpoint is hit the toolbar on the right side shows the Stacktrace and the Variables. Click the arrow to open the section.
  • Click the arrow next to the variable name to show more details

Using Go packages

To use a public package in your Go application add the line to the top of your program to import the package

import "github.com/aws/aws-sdk-go/service/s3"

If this is the first time you are using the package, the error message appears in the output window of Atom when you save the file

cannot find package “github.com/aws/aws-sdk-go/service/s3” in any of:

C:\Go\src\github.com\aws\aws-sdk-go\service\s3 (from $GOROOT) C:\Users\MY_USERNAME\go\src\github.com\aws\aws-sdk-go\service\s3 (from $GOPATH)

Open a terminal window and execute the command to download the package

go get github.com/aws/aws-sdk-go/service/s3

 

Your first Go application

Programming in GO is quick and fun. You can write a working, compiled application with a few lines of code. In this example, we will use Visual Studio Code to edit the source code, and we have already configured it to start from the command line with the “code” command.

Write your first Go application

Create a directory for your application, let’s call it myapp

mkdir myapp

Open a terminal window in the myapp directory

cd myapp

Initialize the Go Modules. Go modules are available since Go version  1.11, in Go version 1.13 is the default over $GOPATH. In the main directory of your application execute

go mod init github.com/MY_USER_NAME/myapp

When we add an import statement to the code, Go will automatically update the go.mod file to include the dependency with the latest stable version. To list the referenced modules execute

go list -m all

Create a file for your module. This file is not required, but as it is on the top level, the package name is considered to be the name of the module.

code config.go

Enter to code

package myapp

func Config() string {
	return "Application config"
}

Create a sub-directory for the entry point of your application. When someone imports your application as a module this will be the command to execute.

mkdir -p cmd/myapp

Create the file for the command

code cmd/myapp/myapp.go

Create the main function

package main

import (
	"fmt"

	"github.com/MY_USER_NAME/myapp"
)

func main() {
	fmt.Println(myapp.Config())
}

Save the files and run the application

go run cmd/myapp/*

The output should be

Application config

Add a package to the application

mkdir mypackage

Create the package file

code mypackage/mypackage.go

Write the code of the package

package mypackage

func RunMyPackage() string {
	return "MyPackage running"
}

Update the main function to call the new package

code cmd/myapp/myapp.go

Add two lines to the code

package main

import (
	"fmt"

	"github.com/MY_USER_NAME/myapp"
	"github.com/MY_USER_NAME/myapp/mypackage" // NEW LINE
)

func main() {
	fmt.Println(myapp.Config())
	fmt.Println(mypackage.RunMyPackage()) // NEW LINE
}

Save the files and run the application. The output should be

go run cmd/myapp/*

Application config
MyPackage running





Using modules from other applications

To upgrade a module to the latest tagged version for example golang.org/x/text

go get golang.org/x/text

List all available versions of a module, for example, rsc.io/sampler

go list -m -versions rsc.io/sampler

Get a specific version of the module

go get rsc.io/sampler@v1.3.1

To remove unused dependencies from the go.mod and go.sum file

go mod tidy