如何从代码中获取当前的GOPATH [英] How to get current GOPATH from code

查看:975
本文介绍了如何从代码中获取当前的GOPATH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从一段代码中获取当前的 GOPATH



运行时只有 GOROOT

  / / GOROOT返回Go树的根。 
//它使用GOROOT环境变量(如果设置)
//或者在Go构建期间使用的根。
func GOROOT()字符串{
s:= gogetenv(GOROOT)
如果s!={
返回s
}
返回defaultGoroot
}

我可以创建一个具有 GOROOT 替换为 GOPATH ,但是有没有一个buildin?

解决方案 div>

使用 os.Getenv



从文档:


Getenv检索由
键命名的环境变量的值。它返回值,如果变量不是
存在,它将为空。


示例:

 包裹主要

进口(
fmt
os


func main(){
fmt.Println(os.Getenv(GOPATH))
}

$ b

更新为Go 1.8 +



Go 1.8具有默认的GOPATH,通过go /

  package main 

import(
fmt
go / build
os


func main(){
gopath:= os.Getenv(GOPATH)
if gopath =={
gopath = build.Default.GOPATH
}
fmt.Println(gopath)
}


How do I get the current GOPATH from a block of code?

runtime only has GOROOT:

// GOROOT returns the root of the Go tree.
// It uses the GOROOT environment variable, if set,
// or else the root used during the Go build.
func GOROOT() string {
    s := gogetenv("GOROOT")
    if s != "" {
        return s
    }
    return defaultGoroot
}

I could make a function that has GOROOT replaced with GOPATH, but is there a buildin for this?

解决方案

Use os.Getenv

From docs:

Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present.

Example:

package main

import (
    "fmt"
    "os"
    )

func main() {
    fmt.Println(os.Getenv("GOPATH"))
}

Update for Go 1.8+

Go 1.8 has default GOPATH exported via go/build:

package main

import (
    "fmt"
    "go/build"
    "os"
)

func main() {
    gopath := os.Getenv("GOPATH")
    if gopath == "" {
        gopath = build.Default.GOPATH
    }
    fmt.Println(gopath)
}

这篇关于如何从代码中获取当前的GOPATH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆