Skip to content

Instantly share code, notes, and snippets.

View fpawel's full-sized avatar

Pavel Filimonenkov fpawel

View GitHub Profile
@sevkin
sevkin / getfreeport.go
Last active May 14, 2024 08:56
get free port in golang
// GetFreePort asks the kernel for a free open port that is ready to use.
func GetFreePort() (port int, err error) {
var a *net.TCPAddr
if a, err = net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
var l *net.TCPListener
if l, err = net.ListenTCP("tcp", a); err == nil {
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
}

pprof

With a single import _ "net/http/pprof" you can add profiling endpoints to a HTTP server.

package main

import (
	"fmt"
@bxcodec
bxcodec / _struct_to_map.go
Last active May 14, 2024 02:22
Golang Struct To Map Example By JSON tag
/*
This function will help you to convert your object from struct to map[string]interface{} based on your JSON tag in your structs.
Example how to use posted in sample_test.go file.
*/
func structToMap(item interface{}) map[string]interface{} {
res := map[string]interface{}{}
if item == nil {
return res
}
type CartItem = string
type EmptyState = NoItems
type PaidForState = { PaidItems : CartItem list;
Payment : decimal}
type ActiveState = { UnpaidItems : CartItem list; }
type Cart =
| Empty of EmptyState
| Active of ActiveState
| PaidFor of PaidForState
@r0l1
r0l1 / copy.go
Last active March 23, 2024 12:38
Copy a directory tree (preserving permissions) in Go.
/* MIT License
*
* Copyright (c) 2017 Roland Singer [roland.singer@desertbit.com]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: