Problem
之前文章中web framework,分成了handler、module、dao三层,如果要强制不能跨层调用,应该怎么处理?
golang internal
Internal packages
Go's package system makes it easy to structure programs into components with clean boundaries, but there are only two forms of access: local (unexported) and global (exported). Sometimes one wishes to have components that are not exported, for instance to avoid acquiring clients of interfaces to code that is part of a public repository but not intended for use outside the program to which it belongs.
The Go language does not have the power to enforce this distinction, but as of Go 1.4 the
go
command introduces a mechanism to define "internal" packages that may not be imported by packages outside the source subtree in which they reside.To create such a package, place it in a directory named
internal
or in a subdirectory of a directory named internal. When thego
command sees an import of a package withinternal
in its path, it verifies that the package doing the import is within the tree rooted at the parent of theinternal
directory. For example, a package.../a/b/c/internal/d/e/f
can be imported only by code in the directory tree rooted at.../a/b/c
. It cannot be imported by code in.../a/b/g
or in any other repository.For Go 1.4, the internal package mechanism is enforced for the main Go repository; from 1.5 and onward it will be enforced for any repository.
Full details of the mechanism are in the design documen.
Solution
go module一个很重要的特征就是将代码的目录结构与package import path解耦开来。这样handler、module、dao作为单独的go module,在import path上只需要以internal包隔开。在目录结构上可以同时保持平级。
有疑问加站长微信联系(非本文作者)