Ismail H
Ismail H

Reputation: 4489

How to import a third party library to a specific folder

Being very new to Go, I'm trying to import a third party library into a vendor folder. I follow the instructions given by the Go docs, but didn't find anything about third party libraries.

Upvotes: 1

Views: 2783

Answers (1)

Zac Romero
Zac Romero

Reputation: 406

Update (2019)

The Go environment is slowly starting to move away from tools like dep and towards the native Go tooling around modules. While explaining models is outside the scope of this answer, you can look into modules from the following places:

https://blog.golang.org/modules2019 https://github.com/golang/go/wiki/Modules

tldr

Install dep: go get -u github.com/golang/dep/cmd/dep

In your project run: dep init

answer

The easiest way to solve this problem in my opinion is using the dep dependency management tool. This tool is very widely in use and is very easy to use. Here is a typical workflow:

First you should install the dep program.

go get -u github.com/golang/dep/cmd/dep

Now you have access to the dep command. Full documentation can be found here: https://golang.github.io/dep/

This is how you get 3rd party libraries into your vendor directory. In the example below we will use the url router github.com/gorilla/mux.

First, in you code import the libraries like normal.

package main

import "github.com/gorilla/mux"

func main {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    r.HandleFunc("/articles", ArticlesHandler)
    http.Handle("/", r)
}

Now all we have to do to get it sed up is run the dep init command. This will look for all of your imports and create a vendor directory for you with all of your needed dependencies. Note that dep automatically analyzes your imports.

Dep in depth

Once you have initialized dep you can start work on your project as normal. When you add a new library you can run the dep ensure command to get the newly added 3rd party libraries in the vendor directory.

In addition, dep gives you the capability to lock down on particular versions of 3rd party libraries. dep init initializes your project with two files: Gopkg.toml and Gopkg.lock. The Gopkg.toml file contains assertions about which dependencies will be at what version. For example, if you wantted the gorilla mux library to stay at version v1.4.0, you could add the following line to your Gopkg.toml:

[[constraint]]
name = "github.com/gorilla/mux"
version = "=v1.4.0"

Dep also has functionality to upgrade dependencies, remove unused dependencies from vendor, and much more. Look at the documentation for more details. https://golang.github.io/dep/

Upvotes: 3

Related Questions