使用 cmd 和 pkg 布局构建项目 - 构建错误

Ayu*_*lik 5 standards build go

我正在尝试使用 Go 项目布局中描述的布局构建Go 项目

我在 Ubuntu 上使用 go 1.9.2。我的项目布局如下

$GOPATH/src/github.com/ayubmalik/cleanprops
    /cmd
        /cleanprops
            /main.go
    /internal
        /pkg
            /readprops.go
Run Code Online (Sandbox Code Playgroud)

文件 cmd/cleanprops/main.go 指的是 cleanprops 包,即

package main

import (
    "fmt"
    "github.com/ayubmalik/cleanprops"
)

func main() {
    body := cleanprops.ReadProps("/tmp/hello.props")
    fmt.Println("%s", body)
}
Run Code Online (Sandbox Code Playgroud)

Internal/pkg/readprops.go 的内容是:

package cleanprops

import (
    "fmt"
    "io/ioutil"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func ReadProps(file string) string {
    body, err := ioutil.ReadFile(file)
    check(err)
    fmt.Println(string(body))
    return body
}
Run Code Online (Sandbox Code Playgroud)

但是,当我从目录 $GOPATH/src/github.com/ayubmalik/cleanprops 内部构建 cmd/cleanprops/main.go 时,使用命令:

go build cmd/cleanprops/main.go 
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

cmd/cleanprops/main.go:5:2: no Go files in /home/xyz/go/src/github.com/ayubmalik/cleanprops
Run Code Online (Sandbox Code Playgroud)

我缺少什么?

Cer*_*món 5

该文件建议采用这种结构:

$GOPATH/src/github.com/ayubmalik/cleanprops
    /cmd
        /cleanprops
            /main.go
    /internal
        /pkg
            /cleanprops
                /readprops.go
Run Code Online (Sandbox Code Playgroud)

像这样导入包。导入路径与$GOPATH/src下面的目录结构匹配。

package main

import (
    "fmt"
    "github.com/ayubmalik/cleanprops/internal/pkg/cleanprops"
)

func main() {
    body := cleanprops.ReadProps("/tmp/hello.props")
    fmt.Println("%s", body)
}
Run Code Online (Sandbox Code Playgroud)

  • [关于访问的“内部”魔法](https://docs.google.com/document/d/1e8kOo3r51b2BWtTs_1uADIA5djfXhPT36s6eHVRIvaU/edit)。命名并没有什么魔力。文档中的大部分内容是一个人关于如何布局项目的约定。 (2认同)