I've recently started learning Go and when I decided to put my code in more than 1 file (main.go), a problem emerged. None of the commonly used stuff like log, cache, config, metrics, etc, that I often need are available in other files, even though it belongs to the same "package main". I want to configure my log instance (logrus package) once, based on data from config (viper package). And this is just the beginning, I will soon have a DB instance(?), Cache instance, etc.
What's the best way to solve my problem, what's the best Go practice? How can I follow DRY principle?
If I put my initial log setup into "mylog" package and then import it in each file of each package, how many mylog instances will there be? One for each file/package/? ? Is it efficient?
Also Log and Config depend on each other. I need to log config errors and I need the config to configure the log.
user@host:~/dev/go/src/helloworld$ go build && ./helloworld
# helloworld
./cache.go:10: undefined: Log
./cache.go:17: undefined: Log
main.go:
package main
import (
"fmt"
"time"
"os"
"strconv"
"strings"
"github.com/julienschmidt/httprouter"
"crypto/hmac"
"crypto/sha256"
// "github.com/gin-gonic/gin"
"net"
"net/http"
Log "github.com/Sirupsen/logrus"
// "io/ioutil"
"encoding/json"
"encoding/hex"
"encoding/base64"
"golang.org/x/crypto/bcrypt"
"github.com/asaskevich/govalidator"
"gopkg.in/gomail.v2-unstable"
"github.com/spf13/viper"
)
.
.
.
cache.go:
package main
import (
"github.com/bradfitz/gomemcache/memcache"
)
var conn = memcache.New("10.1.11.1:11211")
func Set(key string, value []byte, ttl int32) error {
Log.Info("Cache: Set: key: " + key)
err := conn.Set(&memcache.Item{Key: key, Value: value, Expiration: ttl})
// fmt.Println(err)
return err
}