Skip to content

Instantly share code, notes, and snippets.

@danielalvarenga
Last active October 3, 2022 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielalvarenga/cf846ed8c4a389a6798b89b246a95b11 to your computer and use it in GitHub Desktop.
Save danielalvarenga/cf846ed8c4a389a6798b89b246a95b11 to your computer and use it in GitHub Desktop.
[ Go / Golang ] Get the current file and line in runtime
package fileline
import (
"fmt"
"os"
"runtime"
"strings"
)
//Location returns an absolute path of the caller file and the line number.
func Location() string {
_, file, line, _ := runtime.Caller(1)
p, _ := os.Getwd()
return fmt.Sprintf("%s:%d", strings.TrimPrefix(file, p), line)
}
package filelinetest
import (
"./fileline"
"github.com/stretchr/testify/require"
"testing"
)
func TestLocation(t *testing.T) {
location := fileline.Location()
require.Equal(t, "/fileline_test.go:10", location)
location = fileline.Location()
require.Equal(t, "/fileline_test.go:13", location)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment