Skip to content

Instantly share code, notes, and snippets.

@ejholmes
Last active August 29, 2015 14:04
Show Gist options
  • Save ejholmes/a70bd4d64fba2a096154 to your computer and use it in GitHub Desktop.
Save ejholmes/a70bd4d64fba2a096154 to your computer and use it in GitHub Desktop.
Go best practices, tips and guidelines

Environment

  • Use Godep to manage dependencies and commit the Godeps/_workspace/src directory so the build will always compile it when you come back six months later.

Style

  • Read through https://code.google.com/p/go-wiki/wiki/CodeReviewComments. Don't be clever, just follow the community guidelines.
  • Install goimports. Have it run automatically when you save a file in your editor.
  • Install go vet. Also have it run when you save a file. It will catch a lot of typos in comments.

Structure

  • The top-level package should be your "core" library and should ideally be the same name as the repo.
  • Default to not splitting something out into a new package. Only create a new package when there's really reason to do so. If there's some code that could live outside of the repo, and be useful to other go projects, that's a good indication of something that should be broken out.
  • HTTP/RCP server packages should go in server/rcp sub-directories and consume the top level-package, if they get too unmanageable in the top-level package.
  • Commands should go in a sub-directories under a cmd directory and be named appropriately (e.g. if your top-level package is called shorty, then the source for the command will be in cmd/shorty/main.go.

HTTP

  • Wrap http.ResponseWriter and http.Request. This allows you to easily add methods for decoding/encoding.

    // ResponseWriter provides convenience methods for sending http responses
    type ResponseWriter struct {
            http.ResponseWriter
    }
    
    // Encode encodes v into the response as JSON.
    func (w *ResponseWriter) Encode(v interface{}) error {
            w.Header().Set("Content-Type", "application/json")
            return json.NewEncoder(w).Encode(v)
    }
  • Use whatever router you want, but wrap it in your own implementation that hides the third party router.

Database

  • Wrap database/sql in your own implementation.

    type DB struct {
            db *sql.DB
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment