Created
January 8, 2023 14:16
-
-
Save manjeettahkur/f44837e7e65ddd128f803302d764d1d3 to your computer and use it in GitHub Desktop.
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
// Slice rules in go programming language | |
starting cap growth factor | |
256 2.0 | |
512 1.63 | |
1024 1.44 | |
2048 1.35 | |
4096 1.30 | |
package main | |
import ( | |
"context" | |
"encoding/json" | |
"fmt" | |
) | |
const X = 10 | |
// Marshal JSON | |
func main() { | |
const ( | |
x = X + X | |
y | |
) | |
fmt.Println(x, y) | |
data, _ := json.Marshal(context.WithValue(context.Background(), "a", "b")) | |
fmt.Println(string(data)) | |
} | |
// How Slice works | |
package main | |
import "fmt" | |
func main(){ | |
a := [...]rune{'M','A','N','J', 'E', 'E', 'T'} | |
fmt.Printf("a: %c \n",a) | |
x := a[:1] | |
y := a[2:] | |
fmt.Printf("x: %c y: %c\n",x, y) | |
x = append(x, y...) | |
fmt.Printf("a: %c \n",a) | |
fmt.Printf("x: %c y: %c\n",x, y) | |
} | |
// How slice work's in go programming language. | |
package main | |
import ( | |
"fmt" | |
"runtime" | |
"unsafe" | |
) | |
type Object struct { | |
B int | |
A int | |
} | |
func main() { | |
a := (-3) % 2 | |
fmt.Println(a) | |
var i *int | |
x := 1.23 | |
fmt.Printf("%p\n", &i) | |
p := unsafe.Pointer(&i) | |
q := (*float64)(unsafe.Pointer(*(*uintptr)(p))) | |
q = &x | |
fmt.Println(q) | |
fmt.Println(p, "-", unsafe.Sizeof(p)) | |
underlyingSlice() | |
showMem() | |
demoOne() | |
showMem() | |
fmt.Println() | |
demoTwo() | |
showMem() | |
} | |
func underlyingSlice() { | |
primes := [6]int{2, 3, 5, 7, 11, 13} | |
var s []int = primes[1:4] | |
fmt.Println(s) | |
fmt.Println(primes) | |
truncate the slice | |
s = s[:0:0] | |
fmt.Println(s) | |
fmt.Println(primes) | |
continuing to append to the slice | |
s = append(s, 15) | |
fmt.Println(s) | |
fmt.Println(primes) | |
} | |
func demoOne() { | |
var a []*Object | |
for i := 0; i < 8; i++ { | |
a = append(a, new(Object)) | |
} | |
fmt.Println(cap(a), len(a)) | |
a = removeObject(a, 5) | |
fmt.Println(cap(a), len(a)) | |
} | |
func demoTwo() { | |
var c []int | |
for i := 0; i < 8; i++ { | |
c = append(c, i) | |
} | |
fmt.Println(cap(c), len(c)) | |
c = removeInt(c, 5) | |
fmt.Println(cap(c), len(c)) | |
} | |
func removeObject(s []*Object, i int) []*Object { | |
old := s | |
s = append(s[:i], s[i+1:]...) | |
old[len(old)-1] = nil | |
return s | |
} | |
func removeInt(s []int, i int) []int { | |
return append(s[:i], s[i+1:]...) | |
} | |
func showMem() { | |
runtime.GC() | |
var memstat runtime.MemStats | |
runtime.ReadMemStats(&memstat) | |
log.Println("Program is using", memstat.Alloc, "bytes") | |
fmt.Println("HeapAlloc is", memstat.HeapAlloc, "bytes") | |
log.Println("MemStats.Sys is", memstat.Sys, "bytes") | |
log.Println("Cumulative count of heap objects freed is", memstat.Frees, "") | |
} | |
func InspectSlice(slice []string) { | |
Capture the address to the slice structure | |
address := unsafe.Pointer(&slice) | |
addrSize := unsafe.Sizeof(address) | |
Capture the address where the length and cap size is stored | |
lenAddr := uintptr(address) + addrSize | |
capAddr := uintptr(address) + (addrSize * 2) | |
Create pointers to the length and cap size | |
lenPtr := (*int)(unsafe.Pointer(lenAddr)) | |
capPtr := (*int)(unsafe.Pointer(capAddr)) | |
Create a pointer to the underlying array | |
addPtr := (*[8]string)(unsafe.Pointer(*(*uintptr)(address))) | |
fmt.Printf("Slice Addr[%p] Len Addr[0x%x] Cap Addr[0x%x]\n", | |
address, | |
lenAddr, | |
capAddr) | |
fmt.Printf("Slice Length[%d] Cap[%d]\n", | |
*lenPtr, | |
*capPtr) | |
for index := 0; index < *lenPtr; index++ { | |
fmt.Printf("[%d] %p %s\n", | |
index, | |
&(*addPtr)[index], | |
(*addPtr)[index]) | |
} | |
fmt.Printf("\n\n") | |
} | |
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"os" | |
"github.com/gin-gonic/gin" | |
zap "go.uber.org/zap" | |
) | |
const ( | |
EnterpriseName = "IBXE-ENTERPRISE" | |
EndPoint = "http://localhost:8080" | |
TimeFormat = "2006-01-02 15:04:05" | |
VERSION = "1.0.0" | |
) | |
type LogFields map[string]interface{} | |
func NewLogger() *zap.SugaredLogger { | |
var config zap.Config | |
debugMode, ok := os.LookupEnv("DEBUG_LOG") | |
fmt.Println("debugMode", debugMode, "ok", ok) | |
debugMode = "true" | |
if true { | |
config = zap.NewDevelopmentConfig() | |
} else { | |
config = zap.NewProductionConfig() | |
} | |
config.Encoding = "json" | |
config.OutputPaths = []string{"stdout"} | |
logger, err := config.Build() | |
if err != nil { | |
panic(err) | |
} | |
return logger.Named(EnterpriseName).Sugar().With( | |
"version", VERSION, | |
"endpoint", EndPoint, | |
"env", "dev", | |
"enterpriseName", EnterpriseName, | |
) | |
} | |
type loggerKey struct{} | |
func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context { | |
return context.WithValue(ctx, loggerKey{}, logger) | |
} | |
func FromContext(ctx context.Context) *zap.SugaredLogger { | |
if logger, ok := ctx.Value(loggerKey{}).(*zap.SugaredLogger); ok { | |
return logger | |
} | |
return NewLogger() | |
} | |
func addContextLog(c *gin.Context, msg string, keysAndValues ...interface{}) (string, []interface{}) { | |
if reqID, exists := c.Get("requestid"); exists { | |
keysAndValues = append(keysAndValues, "reqID", reqID) | |
} | |
return msg, keysAndValues | |
} | |
func main() { | |
r := gin.New() | |
r := gin.Default() | |
[ping] zap logger is used to log | |
and display logs in json format to stdout | |
r.GET("/ping", func(c *gin.Context) { | |
msg, keysAndValues := addContextLog(c, "I'm using contextual structure logging", "userId", "11111") | |
newLogger := NewLogger() | |
logger := WithLogger(c, newLogger) | |
log := FromContext(logger) | |
log.Infow(msg, keysAndValues...) | |
c.JSON(200, gin.H{ | |
"message": "pong", | |
}) | |
}) | |
[pong] standard fmt logger is used to log | |
without structured logging | |
r.GET("/pong", func(c *gin.Context) { | |
log.Printf("I'm a simple logging %s", "Manjeet Singh") | |
c.JSON(200, gin.H{ | |
"message": "ping", | |
}) | |
}) | |
r.Run() | |
} | |
package main | |
import "fmt" | |
type Node struct { | |
Val int | |
Left *Node | |
Right *Node | |
} | |
func main() { | |
p() | |
q() | |
a := &Node{Val: 1} | |
fmt.Println("*int", a) | |
} | |
func p() { | |
f := func(x int) { print(x) } | |
g := func() int { f = nil; return 1 } | |
defer f(g()) | |
} | |
func q() { | |
f := func(x int) { print(x) } | |
g := func() int { f = nil; return 2 } | |
f(g()) | |
} | |
package main | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
type M struct { | |
Name string | |
} | |
func main() { | |
count := 10 | |
results := make(chan string, count) | |
var mutex sync.Mutex | |
for i := 0; i < count; i++ { | |
go someWork(&mutex, results) | |
} | |
for i := 0; i < count; i++ { | |
fmt.Println(<-results) | |
} | |
} | |
func someWork(mut *sync.Mutex, done chan string) { | |
Lock the mutex, go routine getting lock here, | |
is guarranteed to create the timestamp and | |
perform the request before any other | |
mut.Lock() | |
Get the timestamp | |
myTimeStamp := time.Now().Format("15:04:05.00000") | |
prepare http request, do http request | |
free the mutex | |
mut.Unlock() | |
Process response | |
send to done chan the result | |
done <- myTimeStamp | |
} | |
package main | |
func main(){ | |
count := 10 | |
results := make(chan string, count) | |
for i := 0; i < count; i++ { | |
go func() { | |
someWork(results) | |
}() | |
} | |
for i := 0; i < count; i++ { | |
println(<-results) | |
} | |
} | |
func someWork(done chan string) { | |
do some work | |
done <- "done" | |
} | |
package main | |
import "fmt" | |
type FilePrem uint16 | |
const ( | |
Read FilePrem = 1 << iota | |
Write | |
Execute | |
) | |
func(p FilePrem) String() string { | |
switch p{ | |
case Read: | |
return "Read" | |
case Write: | |
return "Write" | |
case Execute: | |
return "Execute kyu" | |
} | |
return fmt.Sprintf("Unknown FilePrem: %d", p) | |
} | |
func main(){ | |
fmt.Println(Execute) | |
fmt.Printf("%d\n", Execute) | |
} | |
package main | |
import "fmt" | |
func main(){ | |
msg := "π = 3.14159265358..." | |
fmt.Printf("%T\n", msg[0]) | |
for _, c := range msg { | |
fmt.Printf("%T\n", c) | |
fmt.Printf("%c\n", c) | |
fmt.Printf("%v\n", c) | |
break | |
} | |
} | |
package main | |
import "fmt" | |
type OSError int | |
func (e *OSError) Error() string { | |
return fmt.Sprintf("OS Error #%d", *e) | |
} | |
func FileExists(path string) (bool, error) { | |
var err error | |
return false, err | |
} | |
func main() { | |
if _, err := FileExists("foo"); err != nil { | |
fmt.Println(err) | |
} else { | |
fmt.Println("File exists!") | |
} | |
} | |
package main | |
import ( | |
"fmt" | |
) | |
type Job struct { | |
State string | |
done chan struct{} | |
} | |
func(j *Job) Wait() { | |
<-j.done | |
} | |
func(j *Job) Done() { | |
j.State = "done" | |
close(j.done) | |
} | |
func main() { | |
ch := make(chan *Job) | |
go func() { | |
j := <-ch | |
j.Done() | |
}() | |
job := Job{"Ready", make(chan struct{})} | |
ch <- &job | |
job.Wait() | |
fmt.Println(job.State) | |
} | |
You can edit this code! | |
Click here and start typing. | |
package main | |
import ( | |
"fmt" | |
"time" | |
"unsafe" | |
) | |
type Board struct { | |
NailsNeeded int | |
NailsDriven int | |
} | |
type NailDriver interface { | |
DriveNail(nailSupply *int, b *Board) | |
} | |
type NailPuller interface { | |
PullNail(nailSupply *int, b *Board) | |
} | |
type NailDriverPuller interface { | |
NailDriver | |
NailPuller | |
} | |
type Mallet struct{} | |
func (Mallet) DriveNail(nailSupply *int, b *Board) { | |
*nailSupply-- | |
b.NailsDriven++ | |
} | |
type Crowbar struct{} | |
func (Crowbar) PullNail(nailSupply *int, b *Board) { | |
b.NailsDriven-- | |
*nailSupply++ | |
} | |
type Contractor struct{} | |
func (Contractor) Fasten(d NailDriver, nailSupply *int, b *Board) { | |
for b.NailsDriven < b.NailsNeeded { | |
d.DriveNail(nailSupply, b) | |
} | |
} | |
func (Contractor) Unfasten(p NailPuller, nailSupply *int, b *Board) { | |
for b.NailsDriven > b.NailsNeeded { | |
p.PullNail(nailSupply, b) | |
} | |
} | |
func (c Contractor) ProcessBoards(dp NailDriverPuller, nailSupply *int, board []Board) { | |
for i := range board { | |
b := &board[i] | |
fmt.Printf("Examining board #%d: %+v\n", i+1, b) | |
switch { | |
case b.NailsDriven < b.NailsNeeded: | |
c.Fasten(dp, nailSupply, b) | |
case b.NailsDriven > b.NailsNeeded: | |
c.Unfasten(dp, nailSupply, b) | |
} | |
} | |
} | |
type TootBox struct { | |
NailDriver | |
NailPuller | |
nails int | |
} | |
type Slice []bool | |
func (s Slice) Length() int { | |
return len(s) | |
} | |
func (s Slice) Modify(i int, x bool) bool { | |
if s == nil { | |
s = make(Slice, i+1) | |
} | |
s[i] = x | |
return true | |
} | |
func (p *Slice) DoNothing() string { | |
return "do nothing" | |
} | |
func (p *Slice) Append(x bool) bool { | |
*p = append(*p, x) | |
return true | |
} | |
type Log struct { | |
Message string | |
time.Time | |
} | |
func main() { | |
ts := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) | |
log := Log{ | |
Message: "Hello, playground", | |
Time: ts, | |
} | |
fmt.Printf("Log: %+v\n", log) | |
Create a slice of strings. | |
slice := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"} | |
fmt.Printf("Slice Length: [%d] Slice Capacity: [%d]\n", len(slice), cap(slice)) | |
inspectSlice(slice) | |
fmt.Println(((*Slice)(nil)).Append(true)) | |
boards := []Board{ | |
{NailsDriven: 2}, | |
{NailsDriven: 3}, | |
{NailsDriven: 1}, | |
{NailsNeeded: 6}, | |
{NailsNeeded: 9}, | |
{NailsDriven: 4}, | |
} | |
tb := TootBox{ | |
NailDriver: Mallet{}, | |
NailPuller: Crowbar{}, | |
nails: 10, | |
} | |
displayState(&tb, boards) | |
var c Contractor | |
c.ProcessBoards(&tb, &tb.nails, boards) | |
} | |
func displayState(tb *TootBox, board []Board) { | |
fmt.Printf("Box: %#v\n", tb) | |
for _, b := range board { | |
fmt.Printf("Board: \t%+v\n", b) | |
} | |
fmt.Println() | |
} | |
func inspectSlice(slice []string) { | |
Capture the address to the slice structure. | |
address := unsafe.Pointer(&slice) | |
aSize := unsafe.Sizeof(address) | |
lenAddr := uintptr(address) + aSize | |
capAddr := uintptr(address) + aSize*2 | |
lenPtr := (*int)(unsafe.Pointer(lenAddr)) | |
capPtr := (*int)(unsafe.Pointer(capAddr)) | |
addPrt := (*[8]string)(unsafe.Pointer(*(*uintptr)(address))) | |
fmt.Printf("Slice Address: [%p] Len Address: [%x] Cap Address: [%x]\n", address, lenAddr, capAddr) | |
fmt.Printf("Slice Length: [%d] Slice Capacity: [%d]\n", *lenPtr, *capPtr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment