Skip to content

Instantly share code, notes, and snippets.

View karrick's full-sized avatar

Karrick McDermott karrick

View GitHub Profile
package main
import (
"bytes"
"log"
"github.com/linkedin/goavro"
)
var (
@karrick
karrick / should_work.go
Created September 25, 2015 20:09
This should work, but does not
package main
import (
"bytes"
"log"
"github.com/linkedin/goavro"
)
var (
package exist
import (
"sync"
"sync/atomic"
)
type ExistCache struct {
growLock sync.RWMutex
indexMask uint64
// ErrorLogHandler returns a new http.Handler that logs HTTP requests that result in response
// errors. The handler will output lines in common log format to the specified io.Writer.
func ErrorLogHandler(next http.Handler, out io.Writer) http.Handler {
const apacheLogFormat = "%s [%s] \"%s\" %d %d %f\n"
const timeFormat = "02/Jan/2006:15:04:05 MST"
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lrw := &loggedResponseWriter{
ResponseWriter: w,
status: http.StatusOK,
// PanicHandler returns a new http.Handler that catches a panic caused by the specified
// http.Handler, and responds with an appropriate http status code and message.
func PanicHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
var text string
switch t := r.(type) {
case error:
text = t.Error()
// GzipHandler returns a new http.Handler that optionally compresses the response text using the
// gzip compression algorithm when the HTTP request's Accept-Encoding header includes the string
// "gzip".
func GzipHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
@karrick
karrick / sortAndMaybeInsertString.go
Created October 19, 2017 18:29
sortAndMaybeInsertString
package sortAndMaybeInsertString
func sortAndMaybeInsertString(s string, a []string) []string {
if len(a) == 0 {
return append(a, s)
}
sort.Strings(a)
i := sort.SearchStrings(a, s)
@karrick
karrick / readStdinWithTimeout.go
Last active February 15, 2018 08:31
Go function that prompts user but has a timeout on standard input
package main
import (
"bufio"
"fmt"
"io"
"os"
"time"
"github.com/karrick/gorill"
@karrick
karrick / pruneEmptyDirectories.go
Created February 15, 2018 08:34
Go function that prunes empty directories from file system hierarchy
package main
import (
"fmt"
"os"
"github.com/karrick/godirwalk"
"github.com/pkg/errors"
)
package main
import "time"
func backoff(retries int, callback func() error) error {
var err error
delay := time.Millisecond
for {
err = callback()
if err == nil {