novalagung
novalagung

Reputation: 11502

How to get path of imported package

I'm having difficulty when trying to get path of imported package. When I print result of os.Getwd() inside imported package, it's showing same path like on main package.

This what I did.

Project structure

enter image description here

lib/lib.go

package lib

import "os"
import "fmt"

func init() {
    dir, _ := os.Getwd()
    fmt.Println("lib.init() :", dir)
}

func GetPath() {
    dir, _ := os.Getwd()
    fmt.Println("lib.GetPath() :", dir)
}

main.go

package main

import "os"
import "fmt"
import "test-import/lib"

func main() {
    dir, _ := os.Getwd()
    fmt.Println("main :", dir)
    lib.GetPath()
}

Result

lib.init() : /Users/novalagung/Documents/go/src/test-import
main : /Users/novalagung/Documents/go/src/test-import
lib.GetPath() : /Users/novalagung/Documents/go/src/test-import

The result of os.Getwd() from lib/lib.go is still same path like on main. What I want is the real path of the package which is /Users/novalagung/Documents/go/src/test-import/lib/

What should I do? Is it possible?

Upvotes: 2

Views: 7948

Answers (2)

iman tung
iman tung

Reputation: 73

PkgPath() only can retrieve the package path for non-pointer

// If the type was predeclared (string, error) or not defined (*T, struct{},
// []int, or A where A is an alias for a non-defined type), the package path
// will be the empty string.
func packageName(v interface{}) string {
    if v == nil {
        return ""
    }

    val := reflect.ValueOf(v)
    if val.Kind() == reflect.Ptr {
        return val.Elem().Type().PkgPath()
    }
    return val.Type().PkgPath()
}

Upvotes: 2

David Budworth
David Budworth

Reputation: 11626

If you can get a reference to something in the package, you can use reflect to get the import path.

Here's an example on Play:

package main

import (
    "bytes"
    "fmt"
    "reflect"
)

func main() {
    var b bytes.Buffer
    fmt.Println(reflect.TypeOf(b).PkgPath())
}

Upvotes: 12

Related Questions