如果问题是微不足道,我表示道歉 - 我对golang很新,并且想了解进口机制。我使用OSX和简单的程序编译并运行良好。
我使用automatic code generator中的swagger editor生成了golang服务器。我已将代码解压缩到/tmp/
中的某个目录中,生成的服务器包含以下main.go
文件:
package main
import (
// WARNING!
// Change this to a fully-qualified import path
// once you place this file into your project.
// For example,
//
// sw "github.com/myname/myrepo/go"
//
sw "./go"
"log"
"net/http"
)
func main() {
log.Printf("Server started")
router := sw.NewRouter()
log.Fatal(http.ListenAndServe(":8080", router))
}
根据评论的预期,go build main.go
失败并出现以下错误:
main.go:11:2:
go/default.go:3:1: expected 'IDENT', found 'import'
/tmp/goserver/go-server-server
├── LICENSE
├── api
│ └── swagger.yaml
├── go
│ ├── README.md
│ ├── app.yaml
│ ├── default.go
│ ├── logger.go
│ └── routers.go
└── main.go
go/default.go
package
import (
"net/http"
)
type Default struct {
}
func QuestionimagePost(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
}
$GOPATH/src
,并将导入更改为sw "sw/go-server-server/go"
,仍然提供main.go:13:2:
go/default.go:3:1: expected 'IDENT', found 'import'
sw
导入的完全限定导入路径应该是什么,这是什么意思?
答案 0 :(得分:2)
以下是诀窍:
blah
)例如。在go / routers.go
package blah
import (
"log"
"net/http"
"time"
)
func Logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s %s %s %s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}
对go/logger.go
和default.go
go/routers.go:7:2: cannot find package "github.com/gorilla/mux"
错误后,go get 'github.com/gorilla/mux'
答案 1 :(得分:1)
您需要将某个路径导出为GOPATH
,例如$HOME/go
。
export GOPATH=$HOME/go
。
然后,您可以将项目放在$GOPATH/src/go-server-server
($HOME/go/src/go-server-server
)中,如果我正确阅读所有内容,您的完全限定路径将为go-server-server/go
。