Skip to content

Instantly share code, notes, and snippets.

@kylelemons
kylelemons / regexpswitch.go
Created August 18, 2011 16:34
Switch on a regex pattern
package main
import "fmt"
import "regexp"
var email = regexp.MustCompile(`^[^@]+@[^@.]+\.[^@.]+$`)
var shortPhone = regexp.MustCompile(`^[0-9][0-9][0-9][.\-]?[0-9][0-9][0-9][0-9]$`)
var longPhone = regexp.MustCompile(`^[(]?[0-9][0-9][0-9][). \-]*[0-9][0-9][0-9][.\-]?[0-9][0-9][0-9][0-9]$`)
func main() {
@kylelemons
kylelemons / pc.go
Created August 23, 2011 00:07
Demonstrate a many-producer-to-one-consumer approach
package main
import (
"flag"
"fmt"
"sync"
)
var (
@kylelemons
kylelemons / enum.go
Created September 8, 2011 18:49
Enum types (bitshifted too)
package main
import (
"fmt"
"strings"
)
type foo int
const (
One foo = iota
@kylelemons
kylelemons / allstop.go
Created September 10, 2011 17:37
Using "close" to stop multiple goroutines
package main
import (
"fmt"
"sync"
)
func main() {
wg := new(sync.WaitGroup)
stop := make(chan bool)
@kylelemons
kylelemons / linearity.go
Created September 11, 2011 06:15
Investigating linearity
package main
import (
"runtime"
"testing"
"flag"
"fmt"
)
func BenchmarkCounting(b *testing.B) {
@kylelemons
kylelemons / git-release.sh
Created September 13, 2011 15:09
Use git to make release branches for Go
set -ve
[[ -z "$1" ]] && echo "Usage: release.sh <branchname>" && exit 1
BRANCH=$(git branch | grep "^\*" | cut -c 3-)
RELEASE="$1"
git branch | cut -c 3- | grep "^${RELEASE}\$" && git checkout $RELEASE || git checkout -b $RELEASE
git merge $BRANCH
git push
git checkout $BRANCH
@kylelemons
kylelemons / race.go
Created September 13, 2011 21:21
A really bad data race
package main
import (
"flag"
"runtime"
)
var (
n = flag.Int("n", 8, "Number of counting functions")
count = flag.Int("max", 1e5, "Number to count down from")
@kylelemons
kylelemons / printbench.go
Created September 14, 2011 21:59
Benchmarking prints
package main
import (
"fmt"
"io"
"os"
. "testing"
)
// Run this with >/dev/null
@kylelemons
kylelemons / udgsend.go
Created September 15, 2011 20:18
Unix Datagram Server/Client
package main
import (
"flag"
"io"
"log"
"net"
"os"
)
@kylelemons
kylelemons / caller.go
Created September 20, 2011 01:12
Get the calling function's package
func GetMyCaller() (pkg, fun string) {
pc, _, _, ok := runtime.Caller(2) // get my(0) caller(1)'s caller(2)
if !ok { return "", "" }
caller := strings.SplitN(runtime.FuncForPC(pc).Name(), ".", 2)
return caller[0], caller[1]
}