golang snippets

bcrypt example in Golang

Tagged bcrypt, golang  Languages go
package main

import (

// NOTE: You need to escape the dollar signs in the hash with \
// HASH="xxx" PASSWORD=xxx go run main.go
func main() {
    hash, ok := os.LookupEnv("HASH")
    if !ok {
        log.Fatal("The HASH environment variable is not set")
    password, ok := os.LookupEnv("PASSWORD")
    if !ok {
        log.Fatal("The PASSWORD environment variable is not set")
    if isMatch(password, hash) {
        log.Printf("Match '%s' == '%s'", hash, password)
    } else {
        log.Printf("Mismatch '%s' != '%s'", hash, password)

func isMatch(password string, hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    return err == nil

How to set the session's time zone to UTC when using Golang's database/sql

Tagged database, golang, session, sql, timestamp  Languages go

Always remember to set the time zone session setting when using database/sql and timestamps, otherwise timestamps will use the database default:

db, err = sql.Open("postgres", "timezone=UTC")
if err != nil {
defer db.Close()
var timezone string
err = db.QueryRow("SHOW timezone").Scan(&timezone)
if err != nil {
log.Println("timezone:", timezone)

Running SET TIME ZONE ‘Africa/Casablanca’; once in a connection won’t work because a pool of connections is used.

Fixing "go get" and "terminal prompts disabled" when pulling private and public repos from gitlab

Tagged github, gitlab, golang  Languages bash

This frustrating error when running go get can be fixed by following these instructions:

go: downloading gitlab.com/christianhellsten/go-xxxx v0.0.0-20200816045911-18af1d03e51a
cmd/go-xxx/main.go:4:2: gitlab.com/christianhellsten/[email protected]: verifying module: gitlab.com/christianhellsten/[email protected]: reading https://sum.golang.org/lookup/gitlab.com/christianhellsten/[email protected]: 410 Gone
    server response:
    not found: gitlab.com/christianhellsten/[email protected]: invalid version: git fetch -f origin refs/heads/*:refs/heads/* refs/tags/*:refs/tags/* in /tmp/gopath/pkg/mod/cache/vcs/1dd4008ad7804a122a243831f561ea1000480bb532c0388829d0f37bc7349fef: exit status 128:
        fatal: could not read Username for 'https://gitlab.com': terminal prompts disabled

Make sure you have the latest go and git versions.

Then run the following commands:

git config --global url.ssh://[email protected]/.insteadOf https://github.com/
git config --global url.ssh://[email protected]/.insteadOf https://gitlab.com/
go env -w GOPRIVATE="gitlab.com/christianhellsten,bitbucket.org/christianhellsten,github.com/christianhellsten"

Specify the Gitlab token in ~/.git-credentials or ~/.netrc.

Now you can enjoy simple things such as pulling your repos from the internet, but you need to remember to set GIT_TERMINAL_PROMPT too: