Importing custom packages in golang

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

Importing custom packages in golang

问题

我有以下文件:

app/main.go
app/server/server.go
app/server/templates.go

main.go 中有一个 import "app/server" 的导入语句,但是在编译时,它报错:

在 app/server 中找到了 server (server.go) 和 templates (templates.go) 两个包

我猜测它对要加载的包感到困惑了?我的意图是 server.go 将设置路由并导入 ./templates.go 来渲染模板。

有没有更好的文件布局方式?我应该将 templates.go 移动到它自己的目录中吗?

英文:

I have the following:

app/main.go
app/server/server.go
app/server/templates.go

main.go has an import statement of import "app/server", but when compiled, it complains about:

found packages server (server.go) and templates (templates.go) in app/server

Im guessing it is confused about which package to load up? My intention is that server.go will setup the routes and import ./templates.go to render templates.

Is there a better way to layout files? Should I move templates.go to it's own directory?

答案1

得分: 4

阅读这个链接:http://golang.org/doc/code.html — 但简而言之:

  • 每个目录一个包/每个包一个目录。你有servertemplates两个包,你应该只有一个package main,如果你尝试编译一个可执行文件而不是一个库。

  • 不要使用"相对"导入。使用完全限定的路径 - 例如,如果你的基本项目是$GOPATH/src/github.com/JohnFromSO/myapp,那么你应该将子包导入为github.com/JohnFromSo/myapp/database

  • 你可能不需要将templates.go拆分为一个单独的包 - 一个好的经验法则是"如果这个包独立存在,或者可以被其他人使用,那么它是否可用?"

另一个好的阅读材料是https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091

英文:

Read this: http://golang.org/doc/code.html — but in short:

  • One package per directory/one directory per package. You have both server and templates packages where you should just have one - package main if you are attempting to compile a binary and not a library.

  • Don't use "relative" imports. Use the fully qualified path - i.e. if your base project is $GOPATH/src/github.com/JohnFromSO/myapp then you would import sub-packages as github.com/JohnFromSo/myapp/database.

  • You probably don't need to split out templates.go into a separate package - a good rule of thumb is "would this package be usable if it stood on its own/usable by others?"

Another good read is https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091

huangapple
  • 本文由 发表于 2014年7月18日 13:14:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/24817661.html
匿名

发表评论

匿名网友

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

确定