I have a main function, where I initiate a variable, a client. For example:
func main() {
myClient := my.MustNewClient("localhost")
}
Now I want to pass this client to another package, but for some reason I cannot figure out how to do this. My package looks like this:
package rest
import (
"net/http"
"github.com/Sirupsen/logrus"
)
type AssetHandler struct {
mc my.Client
}
func (f AssetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logrus.Info("bla")
// here I want to use the client
mc.SomeFunctionIntheClient()
}
So my question is, how do I use the client (out of main) in my package?
In the package rest you have to add a constructor function like:
func NewAssetHandler(mc my.Client) AssetHandler {
return AssetHandler{mc}
}
Then you have to instantiate the handler from your main function.
Otherwise you would have to create a separate package where you store global variables. The main package itself can not be used for this because it can't be accessed from somewhere else.