Search code examples
gobuildstandards

Go build project with cmd and pkg layout - build error


I'm trying to build a Go project using the layout as described in Go Project Layout

I'm using go 1.9.2 on Ubuntu. My project layout is as follows

$GOPATH/src/github.com/ayubmalik/cleanprops
    /cmd
        /cleanprops
            /main.go
    /internal
        /pkg
            /readprops.go

The file cmd/cleanprops/main.go is referring to the cleanprops package i.e.

package main

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

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

The contents of internal/pkg/readprops.go are:

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
}

However when I build cmd/cleanprops/main.go, from inside directory $GOPATH/src/github.com/ayubmalik/cleanprops, using command:

go build cmd/cleanprops/main.go 

I get the following error:

cmd/cleanprops/main.go:5:2: no Go files in /home/xyz/go/src/github.com/ayubmalik/cleanprops

What am I missing?


Solution

  • The document suggests this structure:

    $GOPATH/src/github.com/ayubmalik/cleanprops
        /cmd
            /cleanprops
                /main.go
        /internal
            /pkg
                /cleanprops
                    /readprops.go
    

    Import the package like this. The import path matches the directory structure below $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)
    }