abutil: github.com/bahlo/abutil Index | Examples | Files

package abutil

import "github.com/bahlo/abutil"

Index

Examples

Package Files

concurrency.go database.go http.go signals.go

func OnSignal Uses

func OnSignal(fn func(os.Signal))

OnSignal calls the given function on the signals SIGHUP, SIGINT, SIGTERM and SIGQUIT

Code:

done := make(chan bool)

go OnSignal(func(s os.Signal) {
    fmt.Printf("Got signal %s\n", s)

    done <- true
})

// Emulate SIGINT
time.AfterFunc(10*time.Millisecond, func() {
    syscall.Kill(syscall.Getpid(), syscall.SIGINT)
})

// Wait until we got our signal
<-done

Output:

Got signal interrupt

func Parallel Uses

func Parallel(n int, fn func())

Parallel runs a given function n times concurrently NOTE: Please set runtime.GOMAXPROCS to runtime.NumCPU() for best performance

The most basic call

Code:

var m sync.Mutex

c := 0
Parallel(4, func() {
    m.Lock()
    defer m.Unlock()

    fmt.Print(c)
    c++
})

Output:

0123

If you need to pass parameters to your function, just wrap it in another and call the superior function immeditately.

Code:

fn := func(someParam, someOtherParam string) func() {
    return func() {
        fmt.Print(someParam, someOtherParam)
    }
}

Parallel(4, fn("foo", "bar"))

func RemoteIP Uses

func RemoteIP(r *http.Request) string

RemoteIP tries to get the remote ip and returns it or ""

Code:

someHandler := func(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("New request from %s\n", RemoteIP(r))
}

// Get's called with RemoteAddr = 123.456.7.8
remoteIPMockServe(someHandler)

Output:

New request from 123.456.7.8

func RollbackErr Uses

func RollbackErr(tx *sql.Tx, alt error) error

RollbackErr does a rollback on the transaction and returns either the error from the rollback if there was one or the alternative. This is useful if you have multiple statments in a row but don't want to call rollback and check for errors every time.

Code:

insertSomething := func(db *sql.DB) error {
    tx, _ := db.Begin()

    _, err := tx.Exec("INSERT INTO some_table (some_column) VALUES (?)",
        "foobar")
    if err != nil {
        // The old way, imagine doing this 10 times in a method
        if err := tx.Rollback(); err != nil {
            return err
        }

        return err
    }

    _, err = tx.Exec("DROP DATABASE foobar")
    if err != nil {
        // With RollbackErr
        return RollbackErr(tx, err)
    }

    return nil
}

exampleRollbackDBContext(func(db *sql.DB) {
    fmt.Println(insertSomething(db))
})

type GracefulServer Uses

type GracefulServer struct {
    *graceful.Server
    // contains filtered or unexported fields
}

GracefulServer is basically graceful.Server (github.com/tylerb/graceful), but adds a state variable to check if stopped and doesn't listen on signals (use OnSignal instead)

Code:

s := NewGracefulServer(1337,
    http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Foo bar"))
    }))

// This channel blocks until all connections are closed or the time is up
sc := s.StopChan()

// Some go func that stops the server after 2 seconds for no reason
time.AfterFunc(1*time.Second, func() {
    fmt.Print("Stopping server..")
    s.Stop(10 * time.Second)
})

if err := s.ListenAndServe(); err != nil && !s.Stopped() {
    // We didn't stop the server, so something must be wrong
    panic(err)
}

// Wait for the server to finish
<-sc
fmt.Print("bye!")

Output:

Stopping server..bye!

func NewGracefulServer Uses

func NewGracefulServer(p int, h http.Handler) *GracefulServer

NewGracefulServer creates a new GracefulServer with the given handler, which listens on the given port.

func (*GracefulServer) ListenAndServe Uses

func (g *GracefulServer) ListenAndServe() error

ListenAndServe is equivalent to http.Server.ListenAndServe with graceful shutdown enabled

func (*GracefulServer) ListenAndServeTLS Uses

func (g *GracefulServer) ListenAndServeTLS(cf, kf string) error

ListenAndServeTLS is equivalent to http.Server.ListenAndServeTLS with graceful shutdown enabled

func (*GracefulServer) ListenAndServeTLSConfig Uses

func (g *GracefulServer) ListenAndServeTLSConfig(c *tls.Config) error

ListenAndServeTLSConfig is equivalent to http.Server.ListenAndServeTLSConfig with graceful shutdown enabled

func (*GracefulServer) Serve Uses

func (g *GracefulServer) Serve(l net.Listener) error

Serve is equivalent to http.Server.Serve with graceful shutdown enabled

func (*GracefulServer) Stopped Uses

func (g *GracefulServer) Stopped() bool

Stopped returns if the server is stopped

Package abutil imports 11 packages (graph). Updated 2018-10-21. Refresh now. Tools for package owners.