Skip to content

Instantly share code, notes, and snippets.

View 0xc0d's full-sized avatar

Ali Josie 0xc0d

View GitHub Profile
@0xc0d
0xc0d / Loop4.go
Last active October 25, 2020 11:53
Using defer in loop
var mutex sync.Mutex
type Person struct {
Age int
}
persons := make([]Person, 10)
for _, p := range persons {
mutex.Lock()
// defer mutex.Unlock()
p.Age = 13
mutex.Unlock()
@0xc0d
0xc0d / Loop4_fix.go
Created October 25, 2020 12:01
Using defer in loop
var mutex sync.Mutex
type Person struct {
Age int
}
persons := make([]Person, 10)
for _, p := range persons {
func() {
mutex.Lock()
defer mutex.Unlock()
p.Age = 13
@0xc0d
0xc0d / unguaranteed_chan.go
Last active October 25, 2020 12:21
Sending into unguaranteed channel
func doReq(timeout time.Duration) obj {
// ch :=make(chan obj)
ch := make(chan obj, 1)
go func() {
obj := do()
ch <- result
} ()
select {
case result = <- ch :
return result
@0xc0d
0xc0d / badOrderedStruct.go
Last active October 25, 2020 15:14
bad ordered struct
type BadOrderedPerson struct {
Veteran bool // 1 byte
Name string // 16 byte
Age int32 // 4 byte
}
type OrderedPerson struct {
Name string
Age int32
Veteran bool
@0xc0d
0xc0d / BadOrderedStruct_Compiler.go
Last active October 27, 2020 15:43
What happen to struct typed inside comiler
type BadOrderedPerson struct {
Veteran bool // 1 byte
_ [7]byte // 7 byte: padding for alignment
Name string // 16 byte
Age int32 // 4 byte
_ struct{} // to prevent unkeyed literals
// zero sized values, like struct{} and [0]byte occurring at
// the end of a structure are assumed to have a size of one byte.
// so padding also will be addedd here as well.
@0xc0d
0xc0d / init.go
Created October 27, 2020 14:00
net http pprof init
func init() {
http.HandleFunc("/debug/pprof/", Index)
http.HandleFunc("/debug/pprof/cmdline", Cmdline)
http.HandleFunc("/debug/pprof/profile", Profile)
http.HandleFunc("/debug/pprof/symbol", Symbol)
http.HandleFunc("/debug/pprof/trace", Trace)
}
@0xc0d
0xc0d / server.go
Created October 27, 2020 14:09
Run http server
func init() {
go func() {
http.ListenAndServe(":1234", nil)
}()
}
@0xc0d
0xc0d / profile.go
Created October 27, 2020 14:35
Dave Cheney Profile
func main() {
defer profile.Start(profile.ProfilePath(".")).Stop()
// do something
}
@0xc0d
0xc0d / allProfiles.go
Created October 27, 2020 14:58
Different profiles in pkg/profile
// CPUProfile enables cpu profiling. Note: Default is CPU
defer profile.Start(profile.CPUProfile).Stop()
// GoroutineProfile enables goroutine profiling.
// It returns all Goroutines alive when defer occurs.
defer profile.Start(profile.GoroutineProfile).Stop()
// BlockProfile enables block (contention) profiling.
defer profile.Start(profile.BlockProfile).Stop()
@0xc0d
0xc0d / http.go
Last active October 27, 2020 19:33
simple buggy http server
import (
"encoding/json"
"math/rand"
"net/http"
_ "net/http/pprof"
"time"
)
func main() {
http.HandleFunc("/log", logHandler)