Structuring a multi-executable Go project

I am trying to build a micro-services architecture project in Go. I am currently using Go 1.11 which supports modules, so I put my root directory in an arbitrary chosen directory, outside of GOPATH.

If I am getting the micro-services architecture concepts right, although my microservices need to be independent, they can share dependencies (and I don’t see another way to do stuff, is it?)

Below is my directory structure:

.
├── go.mod
├── lambda
│   └── account_create
│       └── main.go
├── readme.md
└── types
    ├── account.go
    ├── location.go
    ├── order.go
    ├── pricing.go
    ├── product.go
    └── types.go

Now the behavior I expected was to be able to run go build lambda/account_create and get an executable with that functionality so I can supply it to the respective AWS Lambda function.

However, when I run the command, I get:

can't load package: package lambda/account_create: unknown import path "lambda/account_create": cannot find module providing package lambda/account_create

Please explain me why this does not work and give me some advice on how a project like this should look.

Thank you very much!

What is your module name in go.mod?

By the way (not related to this problem), your package name does not fit the Go naming conventions:

The style of names typical of another language might not be idiomatic in a Go program. Here are two examples of names that might be good style in other languages but do not fit well in Go:

computeServiceClient
priority_queue

https://blog.golang.org/package-names

Try to use vendor folder in your project root, like this:

├── vendor
│   └── lambda
│           └── account_create
│                   └── main.go

and add in your main or whatever

import "lambda/account_create"
1 Like

Why vendor? He uses Go 1.11.

1 Like

I missed that point. I tried the following simple example which work.

Folder tree (let’s suppose somewhere in $HOME):

├── $HOME
│   └── projects
│          └── lambda
│                  ├── account_create
│                  |      └── main.go
│                  └──  main.go

projects/lambda/account_create/main.go

package account_create

func A() {
    println("Hello from account_create")
}

projects/lambda/main.go

package main

import "projects/lambda/account_create"

func main() {
    account_create.A()
    println("Hello from main")
}

Create go.mod. Don’t miss this step because will not work.

cd $HOME/projects/lambda
go mod init projects/lambda

Compile and run the example:

go build
./lambda
Hello from account_create
Hello from main

Of course adjust as you need. Also look over Dave Cheney’s short article about modules.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.