github.com/go-playground/pkg/v5@v5.29.1/runtime/stack.go (about)

     1  package runtimeext
     2  
     3  import (
     4  	"runtime"
     5  	"strings"
     6  )
     7  
     8  // Frame wraps a runtime.Frame to provide some helper functions while still allowing access to
     9  // the original runtime.Frame
    10  type Frame struct {
    11  	runtime.Frame
    12  }
    13  
    14  // File is the runtime.Frame.File stripped down to just the filename
    15  func (f Frame) File() string {
    16  	name := f.Frame.File
    17  	i := strings.LastIndexByte(name, '/')
    18  	return name[i+1:]
    19  }
    20  
    21  // Line is the line of the runtime.Frame and exposed for convenience.
    22  func (f Frame) Line() int {
    23  	return f.Frame.Line
    24  }
    25  
    26  // Function is the runtime.Frame.Function stripped down to just the function name
    27  func (f Frame) Function() string {
    28  	name := f.Frame.Function
    29  	i := strings.LastIndexByte(name, '.')
    30  	return name[i+1:]
    31  }
    32  
    33  // Stack returns a stack Frame
    34  func Stack() Frame {
    35  	return StackLevel(1)
    36  }
    37  
    38  // StackLevel returns a stack Frame skipping the number of supplied frames.
    39  // This is primarily used by other libraries who use this package
    40  // internally as the additional.
    41  func StackLevel(skip int) (f Frame) {
    42  	var frame [3]uintptr
    43  	runtime.Callers(skip+2, frame[:])
    44  	frames := runtime.CallersFrames(frame[:])
    45  	f.Frame, _ = frames.Next()
    46  	return
    47  }