英文:
Go package naming
问题
你可以在main.go
中正确引用项目包。根据你提供的文件结构,你可以使用相对路径来引用sbp/controllers
。
在main.go
中,你可以这样引用sbp/controllers
:
import (
...
"./sbp"
)
...
func main() {
...
r.Get("/", sbp.GetInvestments)
...
}
这样,你就可以从main.go
中调用sbp/controllers
中的GetInvestments
函数了。
另外,你提到尝试过引入sbp/controller
或github.com/jiewmeng/finance/sbp/controller
,但它们似乎被你的VSCode自动删除了。这可能是因为这些引用路径是无效的或不存在的。确保你在引用时使用正确的路径。
英文:
How do I reference project packages correctly? I have the following folder structure:
/sbp
/models.go
/controllers.go
/main.go
In main.go
I'd like to call my controller action from sbp.controllers
. I can't seem to find a way to correctly reference it
main.go
package main
import (
"net/http"
...
"github.com/pressly/chi"
)
var sess = session.Must(session.NewSession(&aws.Config{
Region: aws.String("ap-southeast-1"),
}))
var dynamo = dynamodb.New(sess)
func main() {
r := chi.NewRouter()
r.Get("/", GetInvestments) // How do I call sbp.controller.GetInvestments?
r.Post("/", AddInvestment)
http.ListenAndServe(":8080", r)
}
sbp/controller.go
package sbp
import (
"net/http"
"time"
"github.com/pressly/chi/render"
)
// AddInvestment Adds an investment
func AddInvestment(w http.ResponseWriter, r *http.Request) {
...
}
// GetInvestments Gets list of investments
func GetInvestments(w http.ResponseWriter, r *http.Request) {
...
}
I tried importing "sbp/controller", or even "github.com/jiewmeng/finance/sbp/controller" but they seem to be auto removed my VSCode, so I think its invalid?
答案1
得分: 1
看起来你的编辑器自动运行了goimports
,这意味着它会删除未使用的导入。所以仅仅将它添加到你的imports
部分是不够的;你还必须_使用_这个导入。
看起来你正确的导入路径应该是"github.com/jiewmeng/finance/sbp"。然后你还需要引用它:
package main
import (
// 其他导入
"github.com/jiewmeng/finance/bp"
)
func main() {
// 其他代码
http.Handle("/somepath", http.HandlerFunc(sbp.AddInvestment))
}
英文:
It sounds like your editor is automatically running goimports
, which means it will remove unused imports. So simply adding it to your imports
section isn't good enough; you also have to use the import.
It looks like your proper import path would be "github.com/jiewmeng/finance/sbp". Then you need to reference it as well:
package main
import (
// other imports
"github.com/jiewmeng/finance/bp"
)
func main() {
// whatever
http.Handle("/somepath", http.HandlerFunc(sbp.AddInvestment))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论