【发布时间】:2015-11-13 21:51:04
【问题描述】:
我最近开始学习 Go,当我决定将我的代码放在多个文件 (main.go) 中时,出现了一个问题。我经常需要的日志、缓存、配置、指标等常用的东西在其他文件中都不可用,即使它属于同一个“主包”。我想根据配置(viper 包)中的数据配置我的日志实例(logrus 包)一次。而这仅仅是个开始,我很快就会有一个数据库实例(?)、缓存实例等。
解决我的问题的最佳方法是什么,最佳 Go 实践是什么?如何遵循 DRY 原则?
如果我将我的初始日志设置放入“mylog”包中,然后将其导入每个包的每个文件中,那么将有多少个 mylog 实例?每个文件/包/一个? ?效率高吗?
Log 和 Config 也相互依赖。我需要记录配置错误,我需要配置来配置日志。
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
}
【问题讨论】:
-
“在其他文件中不可用”是什么意思?你在用
go run吗? -
我正在使用“go build”
-
如何调用
go build?你得到什么错误?将此添加到您的问题中。
标签: go dependencies