Go语言中文网 为您找到相关结果 62

golang 获取当前路径和上一级父路径(目录)

golang 获取当前路径和上一级父路径(目录) package main import ( "fmt" "log" "os" "path/filepath" "strings" ) func substr(s string, pos, length int) string { runes := []rune(s) l := pos + length if l > len(runes) { l = len(runes) } return string(runes[pos:l]) } func getParentDirectory(dirctory string) string { return substr(dirctory, 0, strings.LastIndex(dirctory, "...阅读全文

博文 2015-06-17 20:03:59 kuzuozhou

Go语言中Path包用法

// path package main import ( "fmt" "os" "path" "path/filepath" ) func main() { //Path操作 fmt.Println("Path操作-----------------") fmt.Println(path.Base("http://www.baidu.com/file/aa.jpg")) //aa.jpg fmt.Println(path.Clean("c:\\file//abc///aa.jpg")) //c:\file/abc/aa.jpg fmt.Println(os.Getwd()) //D:\Projects\GoPath\source\demo\syntax\path fmt.Prin...阅读全文

博文 2016-04-07 05:00:00 songxingzhu

golang os.Args

package main import( "os" "fmt" ) func main(){ if len(os.Args)!=0{ fmt.Println(os.Args[0])// args 第一个片 是文件路径 } fmt.Println(os.Args[1]) // 第二个参数是, 用户输入的参数 例如 go run osdemo01.go 123 } /* 结果 C:\Users\lyl\AppData\Local\Temp\go-build048711186\command-line-arguments\_obj\exe\osdemo01.exe 123 *...阅读全文

博文 2017-11-15 09:03:06 304158

Golang-相对路径问题

先明确golang中几个参数的含义 之前理解错误了导致自己在写路径时出现了一些问题困惑了好久 特此记录 os.Args[0] 这个参数 并不是什么项目执行路径 获取的是命令行执行语句的第一句 以空格为分隔符 与项目执行路径无丝毫关系 --- 之前理解错了真惭愧啊 os.Getwd() 获取的是运行时你当前所在的路径 比如在/etc 目录下 运行/usr/main文件 最终通过Getwd获取到的值是 /etc golang中的相对路径就是根据这个执行路径来相对的 这也就解释了我 go run 和 idea 启动 还有 supervisor启动 却经常找不到资源的原因 因为所在的执行路径都不一定是相同的自然会这样 所以 一般我现在的做法是 如果是go run 直接到目录地下go run 如果是 ...阅读全文

博文 2015-06-17 20:02:36 u012807459

go filepath Abs

func Abs(path string) (string, error) 检测地址是否是绝对地址,是绝对地址直接返回,不是绝对地址,会添加当前工作路径到参数path前,然后返回 一下是测试代码 func TestAbs() { fpt, err := filepath.Abs("/hello") if err != nil { panic(err) } fmt.Println(fpt) fpt, err = filepath.Abs("helleeo") if err != nil { panic(err) } fmt.Println(fpt) } 打印信息: /hello /home/xxx/workspace/gotestworkspace/golangtest/helleeo “/”...阅读全文

博文 2014-10-04 19:26:08 zongjh

golang中如何获得函数的函数名

如何获取golang中的函数的名字, 这里需要用到反射. 可以看如下代码. 重点使用 runtime.FuncForPC 这个函数获取函数名. 使用strings.FieldsFunc 对得到的带 路径名和包名的 函数名进行必要的处理. package main import ( "fmt" "reflect" "runtime" "strings" // "seps" "runtime/debug" ) func foo() { } func GetFunctionName(i interface{}, seps ...rune) string { // 获取函数名称 fn := runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() ...阅读全文

博文 2018-12-20 17:34:46 个00个

golang 获取当前路径和上一级父路径(目录)

直接贴代码: package main import ( "fmt" "log" "os" "path/filepath" "strings" ) func substr(s string, pos, length int) string { runes := []rune(s) l := pos + length if l > len(runes) { l = len(runes) } return string(runes[pos:l]) } func getParentDirectory(dirctory string) string { return substr(dirctory, 0, strings.LastIndex(dirctory, "/")) } func getCur...阅读全文

博文 2016-11-06 14:00:01 Manrener

go module使用教程:使用go mod的方法.报错go: cannot determine module path for source directory E:\tttttt (outside

使用go mod的方法 单独从大工程里拷出小文件想新建新文件工程时,部分文件路径名报红,出现报错 go: cannot determine module path for source directory E:\tttttt (outside GOPATH, no import comments) 1.在src 目录下新建 go.mod文件 2. go.mod中第一行加入一行内容 module src 3.goland中 file->Settings->Go->Go Modules中勾上 Enable Go Modules(vgo) integration 右键src目录,以goland工程打开,报红消...阅读全文

博文 2019-05-12 17:31:03 ilini

golang在当前执行目录创建日志文件

package main import ( "bufio" "log" "os" "os/exec" "path/filepath" "strings" "time" ) /*获取当前文件执行的路径*/ func GetCurrPath() string { file, _ := exec.LookPath(os.Args[0]) path, _ := filepath.Abs(file) splitstring := strings.Split(path, "\\") size := len(splitstring) splitstring = strings.Split(path, splitstring[size-1]) ret := strings.Replace(splitstri...阅读全文

博文 2014-10-04 19:27:13 xlplbo

golang 多个项目时如何配置(使用gb在非GOPATH路径下构建项目)

方案1:将每个项目路径写入GOPATH 写了个脚本SetGoPath.sh #!/bin/bash if [[ $GOPATH =~ .*$PWD.* ]] then echo "currnet dir is already in GOPATH" else export GOPATH=$GOPATH:$PWD echo "fininsh setting $PWD in GOPATH" fi 在项目主目录中运行source SetGoPath.sh 将当期项目路径写入GOPATH 方案2 使用gb替代go来构建项目 这个gb就是一个替代go的build 和 test的工具,可以让项目在任意路径时运行构建 github地址:https://github.com/constabula... 首先要...阅读全文

博文 2017-03-16 10:00:54 kel

Golang 解决"go get xxxx"失败的问题

【问题1】 sudo go get github.com/nsf/gocode sudo: go: command not found 【解决1】 将已安装的go可执行程序链接到sudo的env路径下,例如下面的操作: sudo ln -s /usr/local/go/bin/go /usr/local/bin/ 【问题2】 sudo go get github.com/nsf/gocode sudo: cannot download, $GOPATH not set. For more details see: go help gopath 【解决2】 将GOPATH路径显式的设置并使用,例如下面的操作: sudo env GOPATH=/Users/ryan/go go get gith...阅读全文

博文 2017-01-05 02:00:01 吃一堑消化不良

protobuf 导入另一文件夹下的proto

环境: protobuf2 ,golang 项目test下 存放proto的目录结构 ---test // 项目根 ------ cs --- cs.proto ------ ss --- ss.proto cs.proto syntax = "proto2"; package cs; message Test{ optional string name = 1; } ss.proto syntax = "proto2"; package ss; import "test/cs/cs.proto"; message Test{ optional cs.Test cstest = 1; } ss.proto 文件引用 cs/cs.proto import 不允许使用相对路径Backslashe...阅读全文

博文 2020-04-23 10:32:51 yddeng

golang 实现对excel的操作

读excel操作 import ( "fmt" "github.com/tealeg/xlsx" ) func main() { excelFileName := "这里是excel的路径" xlFile, error := xlsx.OpenFile(excelFileName) if error != nil { ... } for _, sheet := range xlFile.Sheets { for _, row := range sheet.Rows { for _, cell := range row.Cells { fmt.Printf("%s\n", cell.String()) } } } } 123456789101112131415161718 import ( "...阅读全文

博文 2017-02-10 12:23:35 谢权

go配置sublime text时使用MarGo报错及解决方法

使用sublime text运行go程序,出现如下错误:MarGo: Missing required environment variables: GOROOT GOPATH See the `Quirks` section of USAGE.md for info 解决方法:在sublime->preferenct->package settings->gosublime->settings-user中添加 { "env": { "GOPATH" : "your GOPATH settings",//此处为你的GOPATH路径,如我的为“/home/mygo” "GOROOT" : "your GOROOT settings"//此处为你的GOROOT路径,如我的为“/home/go” ...阅读全文

博文 2015-06-18 09:09:12 chenbaoke

go管理多个项目如何书写gopath以及利用脚本控制项目管理路径

项目组织结构 yishiyaonie:go liuhanlin$ pwd /Users/liuhanlin/qiniuwork/go yishiyaonie:go liuhanlin$ ls aone public qbox 所以设置gopath为pwd的内容:/Users/liuhanlin/qiniuwork/go aone为新项目,public为公共的go库,qbox为第三方库。 提倡的写法 yishiyaonie:go liuhanlin$ $GOPATH -bash: /Users/liuhanlin/qiniuwork/go/public:/Users/liuhanlin/qiniuwork/go/qbox/base/qiniu:/Users/liuhanlin/qiniuwor...阅读全文

博文 2016-08-04 11:00:06 guoer9973

Go获取当前执行路径及图片的加解码

// imagecode.go package main import ( "bytes" "fmt" "os/exec" "path/filepath" "strings" "image" "image/jpeg" "io/ioutil" "os" ) func main() { //读取一张图片,ff为[]byte类型 ff, _ := ioutil.ReadFile("image1.jpg") //把ff写入文件中 _ = ioutil.WriteFile("./output.jpg.txt", ff, 0666) //新建一个缓存 bbb := bytes.NewBuffer(ff) //对byte进行解码 m, _, _ := image.Decode(bbb) //新建一个文件 ...阅读全文

博文 2015-11-01 21:00:06 qq_534019165

gitlab 引用私有仓库(下)

本来以为配置了上篇操作就可以高枕无忧了,没想到,在引用的项目中,出现路径找不到的情况 cannot find module providing package go-sdk/wxsdk/common/comFunc/utilhttp 看了一些引用的官方库,才发现作为私有库的项目中go.mod 和路径要改,以官方的google.golang.org/grpc 项目来看一下 go.mod文件 module google.golang.org/grpc require ( cloud.google.com/go v0.26.0 // indirect github.com/BurntSushi/toml v0.3.1 // indirect github.com/client9/misspell ...阅读全文

博文 2019-03-30 22:34:43 西瓜啊贝贝

golang http.FileServer使用注意点

在一个项目中,我的静态文件比如在static文件夹下,然后我们的URL路径是 .../static/filename(注意这时的URL路径出现了static)其中一种的错误的设置方式http.Handle("/static/",http.FileServer(http.Dir("static"))) 这时候会404, 出现404的原因是 handler会用URL中的路径 此时static去 static目录下找static/filename,而不是想当然的会自动映射。处理:1.你可以在static(实际中的你的目录)下在建立相应URL中的路径的目录结构,2.利用 http.StripPrefix去除http.FileServer会把你传入的作为...阅读全文

博文 2019-04-13 01:34:39 骆鑫_a268

go notepad++ 运行 命令

Notepad++有自己的环境变量 变量名称 含义 FULL_CURRENT_PATH 文件路径名称 CURRENT_DIRECTORY 文件目录 FILE_NAME 文件全名称 NAME_PART 文件名称 EXT_PART 文件扩展名 go语言的 cmd /c 8g $(FULL_CURRENT_PATH) & 8l -o $(CURRENT_DIRECTORY)\$(NAME_PART).exe $(CURRENT_DIRECTORY)\$(NAME_PART).8 & $(CURRENT_DIRECTORY)\$(NAME_PART) & rm -f $(CURRENT_DIRECTORY)\$(NAME_PART).8 & pause 直接 cmd /c go.exe run $(...阅读全文

博文 2014-10-04 19:26:16 悠米海

算法最短路径-Dijkstra(Golang)

//假设有9个节点,图在代码下方,可以参考 shortTablePath存放着V0到Vx某节点的最短路径 该算法,第一次先将V0的节点连接的权值存入shortTablePath,没连接的,用MAXWEIGHT表示.package main import ( "fmt" ) const MAXVEX int = 9 const MAXWEIGHT int = 1000 var shortTablePath = [MAXVEX]int{MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT} func main() { graph := NewGraph()...阅读全文

博文 2017-09-29 04:30:01 zhongxuan

golang中path.Base函数的问题

golang中path.Base(pathString)函数,pathString的值必须为linux风格的路径,即 "/" 才能够正常的获取最后的路径段的值。 在如果路径是windows风格的,即 "\",需要使用 pathfile.ToSlash()函数,将路径转为linux风格。 ```go currentPath, _ := os.Getwd() fmt.Println(currentPath) // D:\go_work\src\test fmt.Println(path.Base(currentPath)) // D:\go_work\src\test currentPath = filepath.ToSlash(currentPath) fmt.Println(currentP...阅读全文

博文 2018-11-02 09:56:38 lijingtian

如何判断zookeeper cluster是否可用

如何判断zookeeper cluster是否可用 还没有找到更好的办法,这个办法很土,就是客户端发起命令一个list命令,看看能不能正确得到结果;list的目标可以是根路径(/),或者其他内置的路径,例如(/zookeeper)。 下面是golang的例子,使用了github.com/samuel/go-zookeeper/zk库文件。 package main import ( "log" "time" "github.com/samuel/go-zookeeper/zk" ) var ZOOKEEPER_SERVERS = []string { "zookeeper1.example.com:2181", "zookeeper2.example.com:2181", "zookeepe...阅读全文

博文 2019-04-01 18:34:42 CodingCode

go语言如何求取二维数组最长路径?

要求: 1. 有N 行,M列整数数字存储在一个txt文件中(如下),每个数字都不重复,同行数字用空格分开(可能为N个空格),将其从文件中读取出来。 2. 以最大的数值作为起点,开始连线,每个数字只能连接其上下左右4个点中的一个,且所连数字必须比当前数字小,求用一条线所能连接的数字的最大个数(注意:不是最大和),输出个数及所连接的数字。 3. 考虑执行效率。 示例: 如文件中存储为如下格式,则25作为起点,可以做25-18-3或25-20-19-4连线 ,而所求的最长连线应为: 25-24-23-22….3-2-1, 共25个。 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 1...阅读全文

Golang - 文件夹遍历

文件夹遍历可以使用filepath.Walk(root string, walkFn filepath.WalkFunc) error来实现,非常方便,root可以是文件夹的绝对路径也可以是文件的绝对路径,但是通常使用文件夹,对文件来说,遍历没有意义。 新建文件traversalFolder.go // traversalFolder.go package main import ( "fmt" "os" "path/filepath" ) func walkFunc(path string, info os.FileInfo, err error) error { if info == nil { // 文件名称超过限定长度等其他问题也会导致info == nil // 如果此时retur...阅读全文

博文 2017-03-05 19:58:44 莫尛莫

golang 的filepath.Walk遇到长路径会报错The system cannot find the path specified.

var size int64 err := filepath.Walk(path, func(p string, info os.FileInfo, err error) error { //处理长路径 if info == nil && err != nil && strings.Contains(err.Error(), syscall.Errno(syscall.ERROR_PATH_NOT_FOUND).Error()) { if p[0:2] == `\\` { //网络路径 p = strings.Replace(p, `\\`, `\\?\UNC\`, 1) info, err = os.Stat(p) } else {//正常路径 info, err = os.Stat(`\...阅读全文

博文 2020-03-27 16:32:45 陈玉涛

go module 学习

go 版本 go version go1.11 darwin/amd64 go module 使用说明 go module 默认为auto模式。 开启配置:export GO111MODULE=on 关闭配置:export GO111MODULE=off auto模式下, 项目在GOPATH/src路径时,需要开启配置为on go module 本地缓存和下载存储路径 GOPATH/pkg/mod 快速入门 go mod 初始化 生产go.mod文件 go mod init moduleName 生成引用包版本信息 go mod tidy -v 或者 go build 项目子包引入 import moduleName/subdir 646B0A5D-92B5-4924-9169-E0910C...阅读全文

博文 2018-11-16 23:34:43 pandanrain

【嗜血GO笔记】引入包的一个异常

我们以User为例cannot use user (type *"models".User) as type *"Service/src/models".User in argument to manager.AddNewUser我们明明用的是一个User 啊,为啥会这样告诉类型不匹配呢?其实这个异常并不是类型不匹配,而是一端我们使用了相对路径引包:"models"而另一端却是:"Service/src/models"这种绝对路径,在go中这种引入方式是不允许的,会被默认为两个struct,所以都改成相对路径或是绝对路径就可以了...阅读全文

博文 2015-02-25 23:00:01 嗜血程序员

go语言:Eclipse与LiteIDE之间路径问题

今天做文件操作的时候,发现了一个路径问题. 当我在使用相对路径进行文件操作时(之前项目是用Eclipse写的),使用"./"得到的路径是基于GoPath的当前路径. 当我今天换成LiteIDE的时候,项目报错了.提示找不到文件,很纳闷找了半天,排查了半天发现,LiteIDE使用"./"是获取当前运行程序所在的当前路径. 与Eclipse环境恰恰相反...阅读全文

博文 2015-06-17 23:07:43 x369201170

go1.13 安装 etcd3.3的问题

安装 etcd 的时候提示错误: cannot find module providing package github.com/coreos/go-systemd/journal 在 go1.12 时提供错误,但编译通过。go1.13错误。解决方式如下: 1.自己从github拉取go-systemd 并保存到 $GOPATH src 下 git clone github.com/coreos/go-systemd 2.使用replace在go.mod中替换go-systemd ## go.mod replace github.com/coreos/go-systemd => /home/xingyys/Go/src/github.com/coreos/go-systemd 这里要注意的是...阅读全文

博文 2019-11-16 11:02:38 xingyys

go管理多个项目如何书写gopath以及利用脚本控制项目管理路径

项目组织结构 yishiyaonie:go liuhanlin$ pwd /Users/liuhanlin/qiniuwork/go yishiyaonie:go liuhanlin$ ls aone public qbox 所以设置gopath为pwd的内容:/Users/liuhanlin/qiniuwork/go aone为新项目,public为公共的go库,qbox为第三方库。 提倡的写法 yishiyaonie:go liuhanlin$ $GOPATH -bash: /Users/liuhanlin/qiniuwork/go/public:/Users/liuhanlin/qiniuwork/go/qbox/base/qiniu:/Users/liuhanlin/qiniuwor...阅读全文

博文 2016-09-06 17:00:07 guoer9973

go web服务(2)

练习:HTTP 处理 实现下面的类型,并在其上定义 ServeHTTP 方法。在 web 服务器中注册它们来处理指定的路径。 type String string type Struct struct { Greeting string Punct string Who string } 例如,可以使用如下方式注册处理方法: http.Handle("/string", String("I'm a frayed knot.")) http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"}) package main import ( "fmt" "log" "net/http" ) type String string type Stru...阅读全文

博文 2016-08-18 13:00:02 chenxun2009

使用文件对象读目录出错了。。。

```go package main import ( "os" "fmt" ) func main(){ f,_ := os.OpenFile("hello.txt",os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777) names,err := f.Readdirnames(2) fmt.Println(err.Error()) for name := range names{ fmt.Println(name) } } ``` 控制台的错误信息说The system cannot find the path specified.(找不到指定的路径) 是不是Readdirnames方法的使用有问...阅读全文

用handlefunc 指向路径时,架设的server 接收请求 总是小概率的卡住,按Ctrl+c 可以继续运行,求助!

用handlefunc 指向路径时,架设的server 接收请求 总是小概率的卡住,按Ctrl+c 可以继续运行,求助! 代码: ```go http.HandleFunc("/product", getProduct) //设定访问的路径 getProduct函数: func getProduct(rw http.ResponseWriter, req *http.Request) { logger.Info("执行getProduct函数") logger.Info("请求类型:[" + req.Method + "]" + "地址:" + req.Host) if req.Method == "GET" { logger.Info("连接数据库....阅读全文

golang 解析html时把url转绝对路径

golang 解析html时把url转绝对路径 在golang解析html时,常遇到img、a标签的资源地址为相对路径[../,./]的情况,这时就需要一个方法把这些地址转换为绝对路径。 // 返回url的绝对地址 // currUrl 当前url func absUrl(currUrl, baseUrl string) string { urlInfo, err := url.Parse(currUrl) if err != nil { return "" } if urlInfo.Scheme != "" { return currUrl } baseInfo, err := url.Parse(baseUrl) if err != nil { return "" } u := base...阅读全文

博文 2020-02-25 22:32:52 _老七