Last active
October 3, 2022 15:20
-
-
Save danielalvarenga/cf846ed8c4a389a6798b89b246a95b11 to your computer and use it in GitHub Desktop.
[ Go / Golang ] Get the current file and line in runtime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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