How can I automatically add dependency packages to go.mod
Initialize the module with go mod init module-path
, this will create the go.mod
file. Build the project with go build
. It automatically adds all dependencies to go.mod
, transitively.
No manual step is involved. The go
tool does everything for you. Of course you may edit the go.mod
file and "fine-tune" the included versions if the automatically chosen ones do not fit your need / intent. See Version Selection how it is done by default.
Note that starting with Go 1.16, go mod tidy
might be needed to add depencencies.
Babr
Updated on June 18, 2022Comments
-
Babr almost 2 years
I have modifed an existing github project with dozens of 3rd party imported packages but I kept the basic structure intact, which is like this:
. ├── config │ ├── config.json │ └── mysql.sql ├── gowebapp.go ├── LICENSE ├── README.md ├── static ├── template │ ├── about │ │ └── about.tmpl │ ├── base.tmpl └── vendor └── app ├── controller │ ├── about.go │ ├── error.go │ ├── index.go │ ├── login.go │ ├── notepad.go │ ├── register.go │ └── static.go ├── model │ ├── model.go │ ├── note.go │ └── user.go ├── route │ ├── middleware │ │ ├── acl │ │ │ └── acl.go │ │ ├── httprouterwrapper │ │ │ └── httprouterwrapper.go │ │ ├── logrequest │ │ │ └── logrequest.go │ │ └── pprofhandler │ │ └── pprofhandler.go │ └── route.go └── shared ├── database │ └── database.go ├── email │ └── email.go ├── jsonconfig │ └── jsonconfig.go ├── passhash │ ├── passhash.go │ └── passhash_test.go ├── recaptcha │ └── recaptcha.go ├── server │ └── server.go ├── session │ └── session.go └── view ├── plugin │ ├── noescape.go │ ├── prettytime.go │ └── taghelper.go └── view.go
Now I want to use go modules to make the project portable.
The main.go imports are like:
package main import ( "encoding/json" "log" "os" "runtime" "app/route" "app/shared/database" "app/shared/email" "app/shared/jsonconfig" "app/shared/recaptcha" "app/shared/server" "app/shared/session" "app/shared/view" "app/shared/view/plugin" )
As you can see the code mostly sits in
vendor/app
folder.I have added several other packages to that.
The problem is that manually adding the packages to go.mod is so tedious, and after all I may miss some imports.
So I'm wondering if there are some automatic tricks to fetch the dependencies to go.mod?