Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang project directory structure

Tags:

I have some confusion regarding Golang directory structure.

Base on the book called <The way to go>, project code should be placed into src, and recommends the following directory structure.

    ├──src/     |  ├──main.go     |  ├──say/     |  |  ├──say.go     |  |  ├──say_test.go     ├──bin/     |  ├──say     └──pkg/        └──linux_amd64/           └──say.a 

but I found that many packages in github.com, have no src directory.

For example:

https://github.com/facebookgo/grace

https://github.com/astaxie/beego

So, I don't know whether src directory is needed.

I have some project, their have inter-dependency. They are managed in a private GitLab repository.

How can I organized them?

like image 946
goosman.lei Avatar asked Oct 09 '17 12:10

goosman.lei


People also ask

How do you structure a go project?

A better way to organize a Go project is to put relevant Go code files into a subdirectory under the main directory for the project so that other parts of the project are able to find the APIs and use them. Keeping all source files under the same directory is not a very good idea, even though you can do it.

Where should I put my Golang code?

Go code must be kept inside a workspace. A workspace is a directory hierarchy with three directories at its root: “src” contains Go source files organized into packages (one package per directory), “pkg” contains package objects, and.

What is CMD folder in go?

/cmd. This folder contains the main application entry point files for the project, with the directory name matching the name for the binary.


1 Answers

This article by Ben Johnson have guided me on this when I was starting with Go.

It's generally good to start with something like this (assuming you are inside your project directory like $GOPATH/src/myproject:

├──cmd/ -- this is where you compose several packages in to main package |  ├──foo -- an example would be `foo` |  |  ├──main.go ├──pkg/ -- this is where put your reusable packages  |  ├──pkg1 -- reusable package 1 |  ├──pkg2 -- reusable package 2 ├──otherpackage1 |  ├── ... ├──otherpackage2 |  ├── ... 

You can have a look at this example from go-kit for this kind of project structure.

Sometimes it will depend on your needs. On our workflow, we are using a hot code reload tool called fresh, so we needed to put the main.go on the project root so that the tool can detect all the file changes and rebuild the source code.

├──app/ |  ├──app.go ├──model/ --  |  ├──model.go ├──store |  ├──store.go ├──main.go -- this is where the app starts ├──... 

On the app.go package, I have something like func Run() error which starts the application. On the main.go, I am just calling the function:

... func main(){     log.Fatal(app.Run()) } 
like image 113
stevenferrer Avatar answered Oct 02 '22 00:10

stevenferrer