golang snippets

bcrypt example in Golang

Tagged bcrypt, golang  Languages go
package main

import (
    "golang.org/x/crypto/bcrypt"
    "log"
    "os"
)

// 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 {
    log.Fatal(err)
}
defer db.Close()
var timezone string
err = db.QueryRow("SHOW timezone").Scan(&timezone)
if err != nil {
    log.Fatal(err)
}
log.Println("timezone:", timezone)

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