Last active
April 20, 2023 19:16
-
-
Save chris-ramon/4223db4405ce5d36c8ac to your computer and use it in GitHub Desktop.
golang notes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// go imports | |
go install golang.org/x/tools/cmd/goimports@latest | |
// enable ms | |
log.SetFlags(log.LstdFlags | log.Lmicroseconds) | |
// count number of tests | |
go test ./... -v | grep -c RUN | |
// diff | |
// https://github.com/kr/pretty | |
fmt.Printf("%+v: ", pretty.Diff(expectedErrors, result.Errors)) | |
// list dependencies of current go project | |
go list -f '{{join .Imports "\n"}}' . | |
// print method caller | |
// fmt.Println(MyCaller()) | |
// MyCaller returns the caller of the function that called it :) | |
func MyCaller() string { | |
// we get the callers as uintptrs - but we just need 1 | |
fpcs := make([]uintptr, 1) | |
// skip 3 levels to get to the caller of whoever called Caller() | |
n := runtime.Callers(3, fpcs) | |
if n == 0 { | |
return "n/a" // proper error her would be better | |
} | |
// get the info of the actual function that's in the pointer | |
fun := runtime.FuncForPC(fpcs[0]-1) | |
if fun == nil { | |
return "n/a" | |
} | |
// return its name | |
return fun.Name() | |
} | |
// Run single subtest | |
go test ./dir/... -run TestSuite/subTest -test.v | |
// running benchmarks, use -run=XYZ to not match any test | |
// runs BenchABC test within a time of 20seconds. | |
go test ./*.go -run=XYZ -bench=BenchABC. -benchtime=20s | |
//errcheck | |
errcheck $(go list ./...) | |
// rebuild libs | |
go install -a | |
// go get all dep | |
go get ./... | |
// go vet | |
go vet ./... | |
// update package | |
go get -u github.com/jinzhu/gorm | |
// inspect var | |
// https://github.com/kr/pretty | |
fmt.Printf("%# v", pretty.Formatter(x)) | |
// packages using a pkg | |
// https://godoc.org/github.com/graphql-go/graphql?importers | |
// sql null fields | |
type Foo { | |
Bar sql.NullInt64 | |
} | |
// set | |
Foo.Bar = sql.NullInt64{Int64: int64(20)} | |
// get | |
Foo.Bar.Int64 | |
# prepend | |
x := append([]int{1}, x...) | |
# anonymous structs | |
data := struct{ Title string }{"Store App!"} | |
# functional options | |
package main | |
import "log" | |
type Product struct { | |
Name string | |
Category Category | |
} | |
type Category struct { | |
Name string | |
} | |
func NewProduct(options ...func(*Product) error) (*Product, error) { | |
var p Product | |
for _, option := range options { | |
if err := option(&p); err != nil { | |
return nil, err | |
} | |
} | |
return &p, nil | |
} | |
func setName(name string) func(*Product) error { | |
return func(p *Product) error { | |
p.Name = name | |
return nil | |
} | |
} | |
func setCategory(name string) func(*Product) error { | |
return func(p *Product) error { | |
p.Category = Category{Name: name} | |
return nil | |
} | |
} | |
func main() { | |
p, err := NewProduct(setName("macbook air"), setCategory("laptop")) | |
if err != nil { | |
log.Fatalf("failed to create new product: %v", err) | |
} | |
log.Printf("product: %+v", p) | |
} | |
# goimports diff | |
$GOPATH/bin/goimports -d main.go | |
# gofmt diff | |
gofmt -d main.go | |
# golint | |
$GOPATH/bin/golint main.go | |
# run one test from root directory | |
go test ./*.go -run TestFieldResolveFnAddsErrorsToGraphQLResult -test.v | |
# run one specific func test | |
go test ./executor -run TestNonNull_NullsAComplexTreeOfNullableFieldsThatThrow | |
# run one test, and import dep files | |
go test ./types/*.go -run TestTypeSystem_Scalar_SerializesOutputInt | |
# null string | |
type Foo struct { | |
SomeField sql.NullString | |
} | |
# get | |
Foo.SomeField.String | |
# set | |
Foo{SomeField: sql.NullString{"bar", true}} | |
# run test include subdir | |
go test ./... | |
# run one test | |
go test server_test.go -test.run TestAbc -test.v | |
# channel | |
assing ownership of data, distributing units of work, communicating async results | |
# mutex | |
caches, state | |
# gorm queries | |
# joins | |
rows, err := DB.Table("purchases").Select("a.id as \"abc\", b.column as \"cba\" ").Joins("inner join b on a.b_id = b.id").Where("a.deleted_at IS NULL OR a.deleted_at <= '0001-01-02'").Where("a.id = ?", A.Id).Rows() | |
defer rows.Close() | |
if err != nil { | |
return err | |
} | |
for rows.Next() { | |
var abc int64 | |
var cba int64 | |
rows.Scan(&abc, &bca) | |
} | |
} | |
# update one | |
if err := DB.Model(abc{}).Where("id = ?", id).Update(abc{ | |
bb: "hi", | |
}).Error; err != nil { | |
} | |
# square selection | |
ctrl + v | |
# int64 to string | |
import "strconv" | |
var i int64 | |
i = 1000 | |
strconv.FormatInt(i, 10), | |
in := fmt.Sprintf("%v", order.Number) | |
# runnign test for specific file | |
go test slugutil_test.go slugutil.go | |
# parse response body | |
body, _ := ioutil.ReadAll(res.Body) | |
t.Logf("BODY: ##### ", string(body)) | |
# type and interfaces conv | |
parsedToken := context.Get(r, "user").(*jwt.Token) | |
log.Printf("parsedToken: %v", reflect.TypeOf(parsedToken)) | |
# run tests and print t.Log | |
go test server_test.go -test.v | |
// debugging | |
// http://lincolnloop.com/blog/introduction-go-debugging-gdb/ | |
// http://www.alexedwards.net/blog/golang-response-snippets#json | |
# build to debug | |
go build -gcflags "-N -l" gdbsandbox.go | |
# quit gdb | |
q | |
# start debugg | |
gdb main | |
# update status code | |
w.WriteHeader(http.StatusNotFound) | |
# run program | |
run | |
# program not running | |
sudo | |
# gopath | |
export GOPATH=$HOME | |
# slides | |
# groupcache | |
http://talks.golang.org/2013/oscon-dl.slide#9 | |
# reflect | |
log.Printf("debug - translations: %v", translations) | |
//for _, t := range translations { | |
//mutable := reflect.ValueOf(event).Elem() | |
//mutable.FieldByName(t.Key).SetString(t.Value) | |
//log.Printf("debug - elem: %v, t: %v", mutable, t) | |
//value := reflect.ValueOf(&event) | |
//elem := value.Elem() | |
//key := elem.FieldByName(t.Key) | |
//if key.IsValid() { | |
//if key.CanSet() { | |
//if key.Kind() == reflect.String { | |
//key.SetString(t.Value) | |
//} | |
//} | |
//} | |
//} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment