DEV Community

Discussion on: Go - Project Structure and Guidelines

Collapse
 
axelrhd profile image
AxelRHD

How is this working with the go run / go build commands? I always got errors. Do I have to change the working directory?

Collapse
 
huholoman profile image
Huholoman • Edited

Your "main.go" files are under cmd. You can make multiple binaries from one project, for example you can have (rest) server which presents app api using rest api interface and then you can have cli, which presents app api using cli interface.

main.go file must be in "main" package to make it buildable/runnable and you can have only one "main" func per package. That means you have to wrap your main.go file to its own folder, so the file struct is

cmd/
    server/
        main.go
    cli/
        main.go
Enter fullscreen mode Exit fullscreen mode

These main.go files just assemble the code together, otherwise your code should be in internal or pkg dirs if you follow the most popular (but not official) project structure.

Now you can run or build any of it by running go run cmd/server or gor run cmd/main.

Now Im not sure, but I think you should name folder and package the same - which we are not doing here in the cmd example, but this nasty hack makes possible to keep multiple main.go files in one place. You could put your main.go in /cmd/(server|cli)/main/main.go tho, but i havent seen this, not a signle once.