Go package naming

huangapple go评论80阅读模式
英文:

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/controllergithub.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))
}

huangapple
  • 本文由 发表于 2017年3月21日 18:59:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/42925162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定