Skip to content

Instantly share code, notes, and snippets.

@wrunk
Last active September 8, 2021 21:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save wrunk/eeea0da770c628eb4067 to your computer and use it in GitHub Desktop.
Save wrunk/eeea0da770c628eb4067 to your computer and use it in GitHub Desktop.
Go cheatsheet
/* This document is for quick ref while learning golang */
// Allocating Slices
// Using slice literals
// Make a slice of strings
strs := []string{"aaa", "bbb", "ccc", "ddd"}
// Bytes
key := []byte("5e8487e6")
// Declaring a var my_slice for later makeage
var my_slice []byte
// Make takes type, length, then capacity (capacity is optional and can be omitted -
// will then default to len)
my_slice = make([]byte, 5, 5)
// my_slice will now be equal to []byte{0, 0, 0, 0, 0}
// Looping
for index, value := range array {
sum += value
}
for i := 0; i < 10; i++ {
sum += i
}
// Printing
// Print all values in a struct
fmt.Printf("%#v\n", cust)
// Print the type of a var (f)
fmt.Println(reflect.ValueOf(f).Kind())
// For slices and strings ? not totally sure on this
fmt.Println(reflect.ValueOf(a).Index(0).Kind())
/*
Structs
Here's some more obscure things you can do with go:
https://talks.golang.org/2012/10things
*/
/*
Interfaces
If you write your structs with an anonymous embedded struct that has the
fields and the getter and setter methods you want, you will get the
effect of interface fields with little extra work on your part.
*/
/*
Maps
*/
// Check if foo is in dict
if val, ok := dict["foo"]; ok {
//do something here
}
// Allocate
var my_map = map[string]string{}
/*
Testing
*/
// Create a file something_test.go (must end with _test.go)
import (
"testing"
"log"
)
func TestMyThing(t *testing.T) {
t.Skip("Skipping")
t.Fail()
}
//
// Sha1ing (hex digested)
//
import (
"crypto/sha1"
"encoding/hex"
)
h := sha1.New()
h.Write([]byte(mid))
h.Write([]byte(session_id))
sha1_hash := hex.EncodeToString(h.Sum(nil))
//
// Gin web server stuff
//
// Get a query string param
token_str := c.Request.URL.Query().Get("access_token")
// Get a param from the path
cid := c.Params.ByName("customer_id")
//
// Working with time
//
created := time.Now().UTC()
expires := created.Add(1*time.Hour)
//
// Get the calling function's name. Try changing the int passed to Caller to go farther up the chain
import "fmt"
import "runtime"
func whoami() string {
pc, _, _, ok := runtime.Caller(1)
if !ok {
return "unknown"
}
me := runtime.FuncForPC(pc)
if me == nil {
return "unnamed"
}
return me.Name()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment