Skip to content

Instantly share code, notes, and snippets.

@eiyaya
Last active November 13, 2018 07:39
Show Gist options
  • Select an option

  • Save eiyaya/1d1d33347aeb345293633c7bf46a0dba to your computer and use it in GitHub Desktop.

Select an option

Save eiyaya/1d1d33347aeb345293633c7bf46a0dba to your computer and use it in GitHub Desktop.

Revisions

  1. eiyaya revised this gist Nov 13, 2018. No changes.
  2. eiyaya revised this gist Nov 13, 2018. 1 changed file with 21 additions and 0 deletions.
    21 changes: 21 additions & 0 deletions GoSafe.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    import (
    "github.com/launchdarkly/foundation/logger"
    "runtime"
    )

    func GoSafely(fn func()) {
    go func() {

    defer func() {
    if err := recover(); err != nil {
    stack := make([]byte, 1024*8)
    stack = stack[:runtime.Stack(stack, false)]

    f := "PANIC: %s\n%s"
    logger.Logger.Error().Printf(f, err, stack)
    }
    }()

    fn()
    }()
    }
  3. eiyaya revised this gist Nov 13, 2018. 1 changed file with 32 additions and 0 deletions.
    32 changes: 32 additions & 0 deletions statedef.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    type ConnState int

    const (
    // StateNew represents a new connection that is expected to
    // send a request immediately. Connections begin at this
    // state and then transition to either StateActive or
    // StateClosed.
    StateNew ConnState = iota

    // StateActive represents a connection that has read 1 or more
    // bytes of a request. The Server.ConnState hook for
    // StateActive fires before the request has entered a handler
    // and doesn't fire again until the request has been
    // handled. After the request is handled, the state
    // transitions to StateClosed, StateHijacked, or StateIdle.
    StateActive

    // StateIdle represents a connection that has finished
    // handling a request and is in the keep-alive state, waiting
    // for a new request. Connections transition from StateIdle
    // to either StateActive or StateClosed.
    StateIdle

    // StateHijacked represents a hijacked connection.
    // This is a terminal state. It does not transition to StateClosed.
    StateHijacked

    // StateClosed represents a closed connection.
    // This is a terminal state. Hijacked connections do not
    // transition to StateClosed.
    StateClosed
    )
  4. eiyaya created this gist Nov 13, 2018.
    12 changes: 12 additions & 0 deletions recover.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    defer func() {
    if err := recover(); err != nil {
    const size = 64 << 10
    buf := make([]byte, size)
    buf = buf[:runtime.Stack(buf, false)]
    c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
    }
    if !c.hijacked() {
    c.close()
    c.setState(origConn, StateClosed)
    }
    }()