I want to push out some of API, from main package into separate package:
myapp/
main.go
myapi/
myapi.go
Inside main.go
i have
package main
import "./myapi"
...
And myapi.go
just starts with:
package myapi
...
When I am trying to run main, it seems like it can't find my myapi
#include
. It gives me following error:
D:\go\myapp> go run .
build _/D_/go/myapp/myapi: cannot find module for path _/D_/go/myapp/myapi
I came from C/C++ world, and it's extremely unobvious, how to include from subfolder in golang. Could you help me with this?
Go uses something called Module Paths. These are paths that identify your packages. They are not necessarily related to the file system.
An example of a module path is
github.com/hajimehoshi/ebiten
.If you're using Go modules, this is also the path Go automatically downloads it from.
If you're using $GOPATH, the path into the source of the module would be
go/src/github.com/hajimehoshi/ebiten
.Initialize your module with a new module path using
go mod init <module path>
. Generally this will be your GitHub repository, without thehttps://
. This will allow for both your and others code to be able accessible using that module path.myapi
should then be accessible viaimport "github.com/username/repo/myapi"
.If you still wish to use the old $GOPATH method, simply place your code inside
go/src/<module path>
. The method of accessingmyapi
is equivalent.Read Using Go Modules and How to write Go code for more information.