Convert Figma logo to code with AI

golang-standards logoproject-layout

Standard Go Project Layout

48,295
5,058
48,295
87

Top Related Projects

26,478

A standard library for microservices.

37,507

A Commander for modern Go CLI interactions

22,151

A simple, fast, and fun package for building command line apps in Go

21,647

Blazing fast, structured, leveled logging in Go.

24,520

Structured, pluggable logging for Go.

77,851

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

Quick Overview

The golang-standards/project-layout repository is a community-driven standard Go project structure and layout. It provides a set of common project directories and basic patterns for organizing Go code. While not an official standard, it aims to offer a consistent and familiar structure for Go projects.

Pros

  • Provides a clear and organized structure for Go projects
  • Helps maintain consistency across different projects and teams
  • Includes explanations for each directory's purpose
  • Widely recognized and adopted in the Go community

Cons

  • Not an official Go standard, which may lead to confusion
  • Some developers argue it's overly complex for smaller projects
  • May not fit all project types or requirements
  • Can be seen as overly prescriptive, potentially limiting creativity

Getting Started

To use this project layout:

  1. Clone the repository:

    git clone https://github.com/golang-standards/project-layout.git
    
  2. Copy the directory structure to your new project:

    cp -R project-layout/* /path/to/your/new/project/
    
  3. Modify the structure as needed for your specific project requirements.

  4. Update the README.md file with your project's information.

  5. Start developing your Go project using this layout as a guide.

Note: This is not a code library, so there are no code examples or specific installation instructions. The project serves as a template and guide for organizing Go projects.

Competitor Comparisons

26,478

A standard library for microservices.

Pros of kit

  • Comprehensive microservices toolkit with ready-to-use components
  • Provides a structured approach to building scalable, distributed systems
  • Includes features like service discovery, load balancing, and circuit breaking

Cons of kit

  • Steeper learning curve due to its extensive feature set
  • May be overkill for smaller projects or simple applications
  • Requires more setup and configuration compared to a basic project layout

Code Comparison

project-layout:

/cmd
    /myapp
        main.go
/internal
    /pkg1
        pkg1.go
    /pkg2
        pkg2.go
/pkg
    /shared
        shared.go

kit:

import (
    "github.com/go-kit/kit/endpoint"
    "github.com/go-kit/kit/transport/http"
)

func makeUppercaseEndpoint(svc StringService) endpoint.Endpoint {
    return func(ctx context.Context, request interface{}) (interface{}, error) {
        req := request.(uppercaseRequest)
        v, err := svc.Uppercase(req.S)
        return uppercaseResponse{v, err}, nil
    }
}

project-layout focuses on providing a standardized directory structure for Go projects, while kit offers a complete toolkit for building microservices. project-layout is simpler and more flexible, suitable for various project types. kit provides more out-of-the-box functionality but may be more complex for beginners or smaller projects.

37,507

A Commander for modern Go CLI interactions

Pros of cobra

  • Provides a robust CLI framework with built-in functionality for command-line parsing, flags, and subcommands
  • Offers auto-generated help and usage information for commands
  • Includes features like command suggestions and bash autocomplete

Cons of cobra

  • More focused on CLI application structure rather than overall project layout
  • May introduce unnecessary complexity for simple projects or non-CLI applications
  • Requires learning cobra-specific concepts and patterns

Code comparison

cobra:

var rootCmd = &cobra.Command{
  Use:   "app",
  Short: "A brief description of your application",
  Run: func(cmd *cobra.Command, args []string) {
    // Your application logic here
  },
}

project-layout:

package main

import (
    "fmt"
    "github.com/yourname/yourproject/pkg/config"
    "github.com/yourname/yourproject/internal/app"
)

func main() {
    cfg := config.Load()
    app.Run(cfg)
}

The cobra example shows how to define a root command for a CLI application, while the project-layout example demonstrates a typical main function structure following the recommended project layout.

22,151

A simple, fast, and fun package for building command line apps in Go

Pros of cli

  • Focused on CLI application development, providing a robust framework for building command-line tools
  • Offers extensive features for parsing command-line arguments, flags, and subcommands
  • Includes built-in help generation and version flagging

Cons of cli

  • Limited to CLI applications, not suitable for broader project structuring
  • May introduce unnecessary complexity for simple command-line tools
  • Requires learning a specific API and conventions for CLI development

Code Comparison

cli:

package main

import (
    "github.com/urfave/cli/v2"
)

func main() {
    app := &cli.App{
        Name:  "greet",
        Usage: "fight the loneliness!",
        Action: func(c *cli.Context) error {
            println("Hello friend!")
            return nil
        },
    }
    app.Run(os.Args)
}

project-layout:

package main

import (
    "fmt"
    "myapp/internal/app"
)

func main() {
    app := app.New()
    fmt.Println(app.Greet())
}

The cli example showcases its focus on CLI application structure, while project-layout demonstrates a more general application structure with separate packages.

21,647

Blazing fast, structured, leveled logging in Go.

Pros of zap

  • Highly optimized, high-performance logging library
  • Structured logging with type-safe field construction
  • Flexible configuration options for various logging scenarios

Cons of zap

  • Focused solely on logging, not a project structure template
  • Steeper learning curve for newcomers to structured logging
  • May be overkill for simple applications with basic logging needs

Code comparison

project-layout:

// No specific code, as it's a project structure template

zap:

logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("Failed to fetch URL",
    zap.String("url", url),
    zap.Int("attempt", attempt),
    zap.Duration("backoff", backoff),
)

Summary

project-layout is a template for organizing Go projects, providing a standardized structure for directories and files. It doesn't include specific functionality but offers guidance on project organization.

zap, on the other hand, is a high-performance logging library for Go. It focuses on structured logging with excellent performance characteristics. While not related to project structure, it's a valuable tool for adding robust logging capabilities to Go applications.

The choice between these repositories depends on the specific needs of your project. If you're looking for guidance on organizing your Go project, project-layout is more suitable. If you need a powerful logging solution, zap is the better choice. In many cases, you might use both: project-layout for structure and zap for logging within that structure.

24,520

Structured, pluggable logging for Go.

Pros of logrus

  • Provides a feature-rich logging framework with structured logging capabilities
  • Offers various output formatters and hooks for customization
  • Supports log levels and field-based logging for better organization

Cons of logrus

  • Focuses solely on logging, unlike project-layout which provides a broader project structure
  • May introduce dependencies and complexity for simple projects
  • Requires learning a specific API, whereas project-layout uses standard Go practices

Code Comparison

logrus:

log := logrus.New()
log.WithFields(logrus.Fields{
    "animal": "walrus",
}).Info("A walrus appears")

project-layout:

// No direct code comparison as project-layout is a directory structure,
// not a logging library. Standard Go logging would be used:
log.Printf("A walrus appears")

Summary

logrus is a powerful logging library for Go, offering structured logging and customization options. project-layout, on the other hand, is a template for organizing Go projects. While logrus enhances logging capabilities, project-layout provides a standardized structure for Go applications. The choice between them depends on whether you need advanced logging features or a project organization guide.

77,851

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

Pros of gin

  • Provides a full-featured web framework with routing, middleware, and HTTP utilities
  • Offers high performance and low memory usage
  • Includes built-in support for JSON validation and rendering

Cons of gin

  • More opinionated and less flexible for custom project structures
  • Steeper learning curve for developers new to web frameworks
  • May include unnecessary features for simple API projects

Code comparison

gin:

r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
    c.JSON(200, gin.H{"message": "pong"})
})
r.Run()

project-layout:

// No specific code structure provided
// Focuses on directory organization rather than framework

Key differences

  • project-layout is a template for organizing Go projects, while gin is a web framework
  • project-layout provides flexibility in choosing libraries and frameworks, gin is a complete solution
  • gin offers ready-to-use features for web development, project-layout requires manual implementation
  • project-layout is suitable for various project types, gin is specifically for web applications

Use cases

  • Choose project-layout for:

    • Large-scale projects with complex structures
    • Projects requiring custom architecture
    • Applications not focused on web development
  • Choose gin for:

    • Rapid development of web applications and APIs
    • Projects prioritizing performance and ease of use
    • Developers familiar with Express-like frameworks

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Standard Go Project Layout

Translations:

Overview

This is a basic layout for Go application projects. Note that it's basic in terms of content because it's focusing only on the general layout and not what you have inside. It's also basic because it's very high level and it doesn't go into great details in terms of how you can structure your project even further. For example, it doesn't try to cover the project structure you'd have with something like Clean Architecture.

This is NOT an official standard defined by the core Go dev team. This is a set of common historical and emerging project layout patterns in the Go ecosystem. Some of these patterns are more popular than others. It also has a number of small enhancements along with several supporting directories common to any large enough real world application. Note that the core Go team provides a great set of general guidelines about structuring Go projects and what it means for your project when it's imported and when it's installed. See the Organizing a Go module page in the official Go docs for more details. It includes the internal and cmd directory patterns (described below) and other useful information.

If you are trying to learn Go or if you are building a PoC or a simple project for yourself this project layout is an overkill. Start with something really simple instead (a single main.gofile andgo.mod is more than enough). As your project grows keep in mind that it'll be important to make sure your code is well structured otherwise you'll end up with a messy code with lots of hidden dependencies and global state. When you have more people working on the project you'll need even more structure. That's when it's important to introduce a common way to manage packages/libraries. When you have an open source project or when you know other projects import the code from your project repository that's when it's important to have private (aka internal) packages and code. Clone the repository, keep what you need and delete everything else! Just because it's there it doesn't mean you have to use it all. None of these patterns are used in every single project. Even the vendor pattern is not universal.

With Go 1.14 Go Modules are finally ready for production. Use Go Modules unless you have a specific reason not to use them and if you do then you don’t need to worry about $GOPATH and where you put your project. The basic go.mod file in the repo assumes your project is hosted on GitHub, but it's not a requirement. The module path can be anything though the first module path component should have a dot in its name (the current version of Go doesn't enforce it anymore, but if you are using slightly older versions don't be surprised if your builds fail without it). See Issues 37554 and 32819 if you want to know more about it.

This project layout is intentionally generic and it doesn't try to impose a specific Go package structure.

This is a community effort. Open an issue if you see a new pattern or if you think one of the existing patterns needs to be updated.

If you need help with naming, formatting and style start by running gofmt and staticcheck. The previous standard linter, golint, is now deprecated and not maintained; use of a maintained linter such as staticcheck is recommended. Also make sure to read these Go code style guidelines and recommendations:

See Go Project Layout for additional background information.

More about naming and organizing packages as well as other code structure recommendations:

A Chinese post about Package-Oriented-Design guidelines and Architecture layer

Go Directories

/cmd

Main applications for this project.

The directory name for each application should match the name of the executable you want to have (e.g., /cmd/myapp).

Don't put a lot of code in the application directory. If you think the code can be imported and used in other projects, then it should live in the /pkg directory. If the code is not reusable or if you don't want others to reuse it, put that code in the /internal directory. You'll be surprised what others will do, so be explicit about your intentions!

It's common to have a small main function that imports and invokes the code from the /internal and /pkg directories and nothing else.

See the /cmd directory for examples.

/internal

Private application and library code. This is the code you don't want others importing in their applications or libraries. Note that this layout pattern is enforced by the Go compiler itself. See the Go 1.4 release notes for more details. Note that you are not limited to the top level internal directory. You can have more than one internal directory at any level of your project tree.

You can optionally add a bit of extra structure to your internal packages to separate your shared and non-shared internal code. It's not required (especially for smaller projects), but it's nice to have visual clues showing the intended package use. Your actual application code can go in the /internal/app directory (e.g., /internal/app/myapp) and the code shared by those apps in the /internal/pkg directory (e.g., /internal/pkg/myprivlib).

You use internal directories to make packages private. If you put a package inside an internal directory, then other packages can’t import it unless they share a common ancestor. And it’s the only directory named in Go’s documentation and has special compiler treatment.

/pkg

Library code that's ok to use by external applications (e.g., /pkg/mypubliclib). Other projects will import these libraries expecting them to work, so think twice before you put something here :-) Note that the internal directory is a better way to ensure your private packages are not importable because it's enforced by Go. The /pkg directory is still a good way to explicitly communicate that the code in that directory is safe for use by others. The I'll take pkg over internal blog post by Travis Jeffery provides a good overview of the pkg and internal directories and when it might make sense to use them.

It's also a way to group Go code in one place when your root directory contains lots of non-Go components and directories making it easier to run various Go tools (as mentioned in these talks: Best Practices for Industrial Programming from GopherCon EU 2018, GopherCon 2018: Kat Zien - How Do You Structure Your Go Apps and GoLab 2018 - Massimiliano Pippi - Project layout patterns in Go).

See the /pkg directory if you want to see which popular Go repos use this project layout pattern. This is a common layout pattern, but it's not universally accepted and some in the Go community don't recommend it.

It's ok not to use it if your app project is really small and where an extra level of nesting doesn't add much value (unless you really want to :-)). Think about it when it's getting big enough and your root directory gets pretty busy (especially if you have a lot of non-Go app components).

The pkg directory origins: The old Go source code used to use pkg for its packages and then various Go projects in the community started copying the pattern (see this Brad Fitzpatrick's tweet for more context).

/vendor

Application dependencies (managed manually or by your favorite dependency management tool like the new built-in Go Modules feature). The go mod vendor command will create the /vendor directory for you. Note that you might need to add the -mod=vendor flag to your go build command if you are not using Go 1.14 where it's on by default.

Don't commit your application dependencies if you are building a library.

Note that since 1.13 Go also enabled the module proxy feature (using https://proxy.golang.org as their module proxy server by default). Read more about it here to see if it fits all of your requirements and constraints. If it does, then you won't need the vendor directory at all.

Service Application Directories

/api

OpenAPI/Swagger specs, JSON schema files, protocol definition files.

See the /api directory for examples.

Web Application Directories

/web

Web application specific components: static web assets, server side templates and SPAs.

Common Application Directories

/configs

Configuration file templates or default configs.

Put your confd or consul-template template files here.

/init

System init (systemd, upstart, sysv) and process manager/supervisor (runit, supervisord) configs.

/scripts

Scripts to perform various build, install, analysis, etc operations.

These scripts keep the root level Makefile small and simple (e.g., https://github.com/hashicorp/terraform/blob/main/Makefile).

See the /scripts directory for examples.

/build

Packaging and Continuous Integration.

Put your cloud (AMI), container (Docker), OS (deb, rpm, pkg) package configurations and scripts in the /build/package directory.

Put your CI (travis, circle, drone) configurations and scripts in the /build/ci directory. Note that some of the CI tools (e.g., Travis CI) are very picky about the location of their config files. Try putting the config files in the /build/ci directory linking them to the location where the CI tools expect them (when possible).

/deployments

IaaS, PaaS, system and container orchestration deployment configurations and templates (docker-compose, kubernetes/helm, terraform). Note that in some repos (especially apps deployed with kubernetes) this directory is called /deploy.

/test

Additional external test apps and test data. Feel free to structure the /test directory anyway you want. For bigger projects it makes sense to have a data subdirectory. For example, you can have /test/data or /test/testdata if you need Go to ignore what's in that directory. Note that Go will also ignore directories or files that begin with "." or "_", so you have more flexibility in terms of how you name your test data directory.

See the /test directory for examples.

Other Directories

/docs

Design and user documents (in addition to your godoc generated documentation).

See the /docs directory for examples.

/tools

Supporting tools for this project. Note that these tools can import code from the /pkg and /internal directories.

See the /tools directory for examples.

/examples

Examples for your applications and/or public libraries.

See the /examples directory for examples.

/third_party

External helper tools, forked code and other 3rd party utilities (e.g., Swagger UI).

/githooks

Git hooks.

/assets

Other assets to go along with your repository (images, logos, etc).

/website

This is the place to put your project's website data if you are not using GitHub pages.

See the /website directory for examples.

Directories You Shouldn't Have

/src

Some Go projects do have a src folder, but it usually happens when the devs came from the Java world where it's a common pattern. If you can help yourself try not to adopt this Java pattern. You really don't want your Go code or Go projects to look like Java :-)

Don't confuse the project level /src directory with the /src directory Go uses for its workspaces as described in How to Write Go Code. The $GOPATH environment variable points to your (current) workspace (by default it points to $HOME/go on non-windows systems). This workspace includes the top level /pkg, /bin and /src directories. Your actual project ends up being a sub-directory under /src, so if you have the /src directory in your project the project path will look like this: /some/path/to/workspace/src/your_project/src/your_code.go. Note that with Go 1.11 it's possible to have your project outside of your GOPATH, but it still doesn't mean it's a good idea to use this layout pattern.

Badges

  • Go Report Card - It will scan your code with gofmt, go vet, gocyclo, golint, ineffassign, license and misspell. Replace github.com/golang-standards/project-layout with your project reference.

    Go Report Card

  • GoDoc - It will provide online version of your GoDoc generated documentation. Change the link to point to your project.

    Go Doc

  • Pkg.go.dev - Pkg.go.dev is a new destination for Go discovery & docs. You can create a badge using the badge generation tool.

    PkgGoDev

  • Release - It will show the latest release number for your project. Change the github link to point to your project.

    Release

Notes

A more opinionated project template with sample/reusable configs, scripts and code is a WIP.