本文整理汇总了Golang中github.com/spf13/viper.GetInt函数的典型用法代码示例。如果您正苦于以下问题:Golang GetInt函数的具体用法?Golang GetInt怎么用?Golang GetInt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GetInt函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: NewStore
func NewStore(stats RuntimeStats) *Storage {
storeType := "memory"
var redisStore *RedisStore
if viper.GetBool("redis_enabled") {
redisHost := viper.GetString("redis_port_6379_tcp_addr")
redisPort := viper.GetInt("redis_port_6379_tcp_port")
connPoolSize := viper.GetInt("redis_connection_pool_size")
numConsumers := viper.GetInt("redis_activity_consumers")
redisStore = newRedisStore(redisHost, redisPort, numConsumers, connPoolSize, stats)
storeType = "redis"
}
var Store = Storage{
&MemoryStore{make(map[string]map[string]*Socket), make(map[string]map[string]*Socket), 0},
redisStore,
storeType,
sync.RWMutex{},
sync.RWMutex{},
}
return &Store
}
开发者ID:mahtuag,项目名称:incus,代码行数:25,代码来源:store.go
示例2: Server
func Server() {
app, err := NewApplication()
if err != nil {
logrus.Fatal(err.Error())
}
middle, err := app.middlewareStruct()
if err != nil {
logrus.Fatal(err.Error())
}
logrus.Printf("Running on http://%s:%d", viper.GetString("bind"), viper.GetInt("port"))
logrus.Printf("IPA server: %s", viper.GetString("ipahost"))
http.Handle("/", middle)
certFile := viper.GetString("cert")
keyFile := viper.GetString("key")
if certFile != "" && keyFile != "" {
http.ListenAndServeTLS(fmt.Sprintf("%s:%d", viper.GetString("bind"), viper.GetInt("port")), certFile, keyFile, nil)
} else {
logrus.Warn("**WARNING*** SSL/TLS not enabled. HTTP communication will not be encrypted and vulnerable to snooping.")
http.ListenAndServe(fmt.Sprintf("%s:%d", viper.GetString("bind"), viper.GetInt("port")), nil)
}
}
开发者ID:HeWhoWas,项目名称:mokey,代码行数:26,代码来源:server.go
示例3: Config
//Config configure Clair from configFile
func Config() {
fmtURI(viper.GetString("clair.uri"), viper.GetInt("clair.port"))
priority = viper.GetString("clair.priority")
healthPort = viper.GetInt("clair.healthPort")
Report.Path = viper.GetString("clair.report.path")
Report.Format = viper.GetString("clair.report.format")
}
开发者ID:wemanity-belgium,项目名称:hyperclair,代码行数:8,代码来源:clair.go
示例4: resetPassword
func resetPassword(app *Application, answer *model.SecurityAnswer, token *model.Token, r *http.Request) error {
ans := r.FormValue("answer")
pass := r.FormValue("password")
pass2 := r.FormValue("password2")
if len(pass) < viper.GetInt("min_passwd_len") || len(pass2) < viper.GetInt("min_passwd_len") {
return errors.New(fmt.Sprintf("Please set a password at least %d characters in length.", viper.GetInt("min_passwd_len")))
}
if pass != pass2 {
return errors.New("Password do not match. Please confirm your password.")
}
if utf8.RuneCountInString(ans) < 2 || utf8.RuneCountInString(ans) > 100 {
return errors.New("Invalid answer. Must be between 2 and 100 characters long.")
}
err := bcrypt.CompareHashAndPassword([]byte(answer.Answer), []byte(ans))
if err != nil {
return errors.New("The security answer you provided does not match. Please check that you are entering the correct answer.")
}
// Setup password in FreeIPA
err = setPassword(token.UserName, "", pass)
if err != nil {
if ierr, ok := err.(*ipa.ErrPasswordPolicy); ok {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": ierr.Error(),
}).Error("password does not conform to policy")
return errors.New("Your password is too weak. Please ensure your password includes a number and lower/upper case character")
}
if ierr, ok := err.(*ipa.ErrInvalidPassword); ok {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": ierr.Error(),
}).Error("invalid password from FreeIPA")
return errors.New("Invalid password.")
}
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to set user password in FreeIPA")
return errors.New("Fatal system error")
}
// Destroy token
err = model.DestroyToken(app.db, token.Token)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to remove token from database")
return errors.New("Fatal system error")
}
return nil
}
开发者ID:HeWhoWas,项目名称:mokey,代码行数:60,代码来源:handlers.go
示例5: OpenRedis
//OpenRedis open redis
func OpenRedis() *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, e := redis.Dial(
"tcp",
fmt.Sprintf(
"%s:%d",
viper.GetString("redis.host"),
viper.GetInt("redis.port"),
),
)
if e != nil {
return nil, e
}
if _, e = c.Do("SELECT", viper.GetInt("redis.db")); e != nil {
c.Close()
return nil, e
}
return c, nil
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
开发者ID:itpkg,项目名称:chaos,代码行数:29,代码来源:utils.go
示例6: OnDisconnect
// OnDisconnect event. Terminates MumbleDJ process or retries connection if
// automatic connection retries are enabled.
func (dj *MumbleDJ) OnDisconnect(e *gumble.DisconnectEvent) {
dj.Queue.Reset()
if viper.GetBool("connection.retry_enabled") &&
(e.Type == gumble.DisconnectError || e.Type == gumble.DisconnectKicked) {
logrus.WithFields(logrus.Fields{
"interval_secs": fmt.Sprintf("%d", viper.GetInt("connection.retry_interval")),
"attempts": fmt.Sprintf("%d", viper.GetInt("connection.retry_attempts")),
}).Warnln("Disconnected from server. Retrying connection...")
success := false
for retries := 0; retries < viper.GetInt("connection.retry_attempts"); retries++ {
logrus.Infoln("Retrying connection...")
if client, err := gumble.DialWithDialer(new(net.Dialer), viper.GetString("connection.address")+":"+viper.GetString("connection.port"), dj.GumbleConfig, dj.TLSConfig); err == nil {
dj.Client = client
logrus.Infoln("Successfully reconnected to the server!")
success = true
break
}
time.Sleep(time.Duration(viper.GetInt("connection.retry_interval")) * time.Second)
}
if !success {
dj.KeepAlive <- true
logrus.Fatalln("Could not reconnect to server. Exiting...")
}
} else {
dj.KeepAlive <- true
logrus.Fatalln("Disconnected from server. No reconnect attempts will be made.")
}
}
开发者ID:matthieugrieger,项目名称:mumbledj,代码行数:31,代码来源:mumbledj.go
示例7: createEventHubServer
func createEventHubServer() (net.Listener, *grpc.Server, error) {
var lis net.Listener
var grpcServer *grpc.Server
var err error
if peer.ValidatorEnabled() {
lis, err = net.Listen("tcp", viper.GetString("peer.validator.events.address"))
if err != nil {
return nil, nil, fmt.Errorf("failed to listen: %v", err)
}
//TODO - do we need different SSL material for events ?
var opts []grpc.ServerOption
if comm.TLSEnabled() {
creds, err := credentials.NewServerTLSFromFile(
viper.GetString("peer.tls.cert.file"),
viper.GetString("peer.tls.key.file"))
if err != nil {
return nil, nil, fmt.Errorf("Failed to generate credentials %v", err)
}
opts = []grpc.ServerOption{grpc.Creds(creds)}
}
grpcServer = grpc.NewServer(opts...)
ehServer := producer.NewEventsServer(
uint(viper.GetInt("peer.validator.events.buffersize")),
viper.GetInt("peer.validator.events.timeout"))
pb.RegisterEventsServer(grpcServer, ehServer)
}
return lis, grpcServer, err
}
开发者ID:hyperledger,项目名称:fabric,代码行数:32,代码来源:start.go
示例8: spikyHorizontalMaze
func spikyHorizontalMaze() *Maze {
z := fullMaze()
ySize := viper.GetInt("height")
xSize := viper.GetInt("width")
middleX := xSize / 2
middleY := ySize / 2
for x := 0; x < xSize; x++ {
for y := 0; y < ySize; y++ {
if x > 0 && x != (middleX+1) {
z.rooms[y][x].Walls.Left = false
}
if x < (xSize-1) && x != middleX {
z.rooms[y][x].Walls.Right = false
}
if x == 0 && y > 0 {
z.rooms[y][x].Walls.Top = false
}
if x == 0 && y < (ySize-1) {
z.rooms[y][x].Walls.Bottom = false
}
if x == (xSize-1) && y > 0 {
z.rooms[y][x].Walls.Top = false
}
if x == (xSize-1) && y < (ySize-1) {
z.rooms[y][x].Walls.Bottom = false
}
}
}
z.rooms[0][middleX].Walls.Right = false
z.rooms[ySize-1][middleX].Walls.Right = false
z.rooms[0][middleX+1].Walls.Left = false
z.rooms[ySize-1][middleX+1].Walls.Left = false
z.rooms[middleY][xSize-1].Walls.Bottom = true
z.rooms[middleY+1][xSize-1].Walls.Top = true
// Random* icarus & treasure
icarusX := rand.Intn(xSize)
icarusY := rand.Intn(ySize)
treasureX := rand.Intn(xSize)
treasureY := rand.Intn(ySize)
// *Don't let them be in the same cell, no fun then
for {
if icarusX != treasureX || icarusY != treasureY {
break
} else {
treasureX = rand.Intn(xSize)
treasureY = rand.Intn(ySize)
}
}
z.SetStartPoint(icarusX, icarusY)
z.SetTreasure(treasureX, treasureY)
return z
}
开发者ID:conejoninja,项目名称:gc6,代码行数:60,代码来源:daedalus.go
示例9: ThreadlessNewStateTransferState
func ThreadlessNewStateTransferState(stack PartialStack) *StateTransferState {
var err error
sts := &StateTransferState{}
sts.stateTransferListenersLock = &sync.Mutex{}
sts.stack = stack
sts.id, _, err = stack.GetNetworkHandles()
if nil != err {
logger.Debug("Error resolving our own PeerID, this shouldn't happen")
sts.id = &protos.PeerID{"ERROR_RESOLVING_ID"}
}
sts.asynchronousTransferInProgress = false
sts.RecoverDamage = viper.GetBool("statetransfer.recoverdamage")
sts.stateValid = true // Assume our starting state is correct unless told otherwise
sts.validBlockRanges = make([]*blockRange, 0)
sts.blockVerifyChunkSize = uint64(viper.GetInt("statetransfer.blocksperrequest"))
if sts.blockVerifyChunkSize == 0 {
panic(fmt.Errorf("Must set statetransfer.blocksperrequest to be nonzero"))
}
sts.initiateStateSync = make(chan *syncMark)
sts.blockHashReceiver = make(chan *blockHashReply, 1)
sts.blockSyncReq = make(chan *blockSyncReq)
sts.threadExit = make(chan struct{})
sts.blockThreadIdle = true
sts.stateThreadIdle = true
sts.blockThreadIdleChan = make(chan struct{})
sts.stateThreadIdleChan = make(chan struct{})
sts.DiscoveryThrottleTime = 1 * time.Second // TODO make this configurable
sts.BlockRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.singleblock"))
if err != nil {
panic(fmt.Errorf("Cannot parse statetransfer.timeout.singleblock timeout: %s", err))
}
sts.StateDeltaRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.singlestatedelta"))
if err != nil {
panic(fmt.Errorf("Cannot parse statetransfer.timeout.singlestatedelta timeout: %s", err))
}
sts.StateSnapshotRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.fullstate"))
if err != nil {
panic(fmt.Errorf("Cannot parse statetransfer.timeout.fullstate timeout: %s", err))
}
sts.MaxStateDeltas = viper.GetInt("statetransfer.maxdeltas")
if sts.MaxStateDeltas <= 0 {
panic(fmt.Errorf("sts.maxdeltas must be greater than 0"))
}
return sts
}
开发者ID:RicHernandez2,项目名称:fabric,代码行数:60,代码来源:statetransfer.go
示例10: GetConnection
func GetConnection() *sql.DB {
if db != nil {
return db
} else {
var err error
db, err = sql.Open("mysql", viper.GetString("connections.onepixel.dsl"))
if err != nil {
log.Fatalf("Error on initializing database connection: %s", err.Error())
}
db.SetMaxIdleConns(viper.GetInt("connections.onepixel.maxIdleConnection"))
db.SetMaxOpenConns(viper.GetInt("connections.onepixel.maxOpenConnection"))
err = db.Ping()
if err != nil {
log.Fatalf("Error on opening database connection: %s", err.Error())
}
return db
}
}
开发者ID:alyakimov,项目名称:pixel,代码行数:25,代码来源:connections.go
示例11: startApp
func startApp(db *gorm.DB) {
log := logging.MustGetLogger("log")
if viper.GetString("logtype") != "debug" {
gin.SetMode(gin.ReleaseMode)
}
g := gin.Default()
//r := NewRessource(db)
g.Use(cors.Middleware(cors.Config{
Origins: "*",
Methods: "GET, PUT, POST, DELETE",
RequestHeaders: "Origin, Authorization, Content-Type",
ExposedHeaders: "",
MaxAge: 50 * time.Second,
Credentials: true,
ValidateHeaders: false,
}))
g.Static("/", "./static")
/*v1 := g.Group("api/v1")
{
v1.GET("/temperatures", r.GetTemperatures)
v1.POST("/temperature", r.PostTemperature)
}*/
log.Debug("Port: %d", viper.GetInt("server.port"))
g.Run(":" + strconv.Itoa(viper.GetInt("server.port")))
}
开发者ID:WnP,项目名称:zut,代码行数:29,代码来源:app.go
示例12: InsertTrack
// InsertTrack inserts track `t` at position `i` in the queue.
func (q *Queue) InsertTrack(i int, t interfaces.Track) error {
q.mutex.Lock()
beforeLen := len(q.Queue)
// An error should never occur here since maxTrackDuration is restricted to
// ints. Any error in the configuration will be caught during yaml load.
maxTrackDuration, _ := time.ParseDuration(fmt.Sprintf("%ds",
viper.GetInt("queue.max_track_duration")))
if viper.GetInt("queue.max_track_duration") == 0 ||
t.GetDuration() <= maxTrackDuration {
q.Queue = append(q.Queue, Track{})
copy(q.Queue[i+1:], q.Queue[i:])
q.Queue[i] = t
} else {
q.mutex.Unlock()
return errors.New("The track is too long to add to the queue")
}
if len(q.Queue) == beforeLen+1 {
q.mutex.Unlock()
q.playIfNeeded()
return nil
}
q.mutex.Unlock()
return errors.New("Could not add track to queue")
}
开发者ID:matthieugrieger,项目名称:mumbledj,代码行数:27,代码来源:queue.go
示例13: SinkFactory
// SinkFactory creates a new object with sinks.Sink interface
func SinkFactory() sinks.Sink {
sinkType := viper.GetString("sink-type")
filename := viper.GetString("filesystem-filename")
maxAge := viper.GetInt("filesystem-max-age")
maxBackups := viper.GetInt("filesystem-max-backups")
maxSize := viper.GetInt("filesystem-max-size")
if sinkType == "filesystem" {
return sinks.NewFilesystemSink(filename, maxAge, maxBackups, maxSize)
}
output := viper.GetString("console-output")
var stdOutput *os.File
if sinkType == "console" {
if output == "stdout" {
stdOutput = os.Stdout
} else if output == "stderr" {
stdOutput = os.Stderr
} else {
log.Warningf("Unknown console output type '%s'. Falling back to 'stdout'", output)
}
return sinks.NewConsoleSink(stdOutput)
}
log.Warningf("Unknown sink type '%s'. Falling back to 'filesystem'", sinkType)
return sinks.NewFilesystemSink(filename, maxAge, maxBackups, maxSize)
}
开发者ID:admiralobvious,项目名称:tinysyslog,代码行数:29,代码来源:factories.go
示例14: launchServer
// launchServer sets up the http fileserver. Exciting!
func launchServer() {
r := mux.NewRouter().
StrictSlash(true)
// Grab all our config junk and prepare to launch
ip := viper.GetString("ListenAddr")
port := viper.GetInt("ListenPort")
fmt.Println(viper.GetInt("ListenPort"))
// I... I guess, if you want TLS, you can totally have it
cert, key := viper.GetString("CertFile"), viper.GetString("KeyFile")
useTLS := len(cert) > 0 && len(key) > 0
scheme := "https"
if !useTLS {
if port == 0 {
port = 80
}
scheme = "http"
} else if port == 0 {
port = 443
}
p := fmt.Sprintf("%s:%d", ip, port)
root, files := viper.GetString("ServerRoot"), viper.GetString("StaticFiles")
reload, err := lr.New(lr.DefaultName, lr.DefaultPort)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
go reload.ListenAndServe()
r.PathPrefix(root).
Handler(
handlers.CombinedLoggingHandler(
os.Stdout, injectReload(root, files, scheme),
),
)
go func() {
fmt.Printf("Launching ogload on %s\n", p)
if !useTLS {
if err := http.ListenAndServe(p, r); err != nil {
fmt.Printf("Server failed! scheme=%s, addr=%s, err=%v\n", scheme, p, err)
os.Exit(1)
}
return
}
if err := http.ListenAndServeTLS(p, cert, key, r); err != nil {
fmt.Printf("TLS Server failed! scheme=%s, addr=%s, err=%v\n", scheme, p, err)
os.Exit(1)
}
}()
wait := watchDir(files, reload)
<-wait
}
开发者ID:pombredanne,项目名称:tools-8,代码行数:60,代码来源:main.go
示例15: GetInt
// GetInt returns a config value as an int.
func (c *LiveConfig) GetInt(ns, key string) int {
if ns == NSRoot {
return viper.GetInt(key)
}
nskey := fmt.Sprintf("%s-%s", ns, key)
return viper.GetInt(nskey)
}
开发者ID:neurodrone,项目名称:doit,代码行数:9,代码来源:doit.go
示例16: CreateShortLink
//Method Creating a short link form a origin url and optionaly a personalized token
//Checks that the origin url exists, that the token does not go over a configured size
//generates random number if token already exist
//generates random string if token is empty
//return new shortlink
func (bm *BusinessManager) CreateShortLink(inToken string, inOrigin string) (outLink *e.ShortLink, err error) {
// function to recover in case of panic while accessing the database
defer func() {
if r := recover(); r != nil {
switch x := r.(type) {
case e.DatabaseError:
err = x
case error:
err = x
case string:
err = errors.New(x)
default:
err = errors.New("Unknown panic")
}
outLink = new(e.ShortLink)
}
}()
// check whether url exists
if !isExistingUrl(inOrigin) {
return outLink, e.InputError{"Bad Request: Specified URL does not exist"}
}
outOrigin := inOrigin
// check personalized token size
if len(inToken) > viper.GetInt("NbMaxCharToken") {
return new(e.ShortLink), e.InputError{"Bad Request: Token too long"}
}
// generate a random root token
if len(inToken) == 0 {
inToken = pickRandomString(viper.GetInt("NbMaxCharToken"))
}
outToken := inToken
// while the token exist
for bm.dalManager.ContainsToken(outToken) {
outToken = inToken + pickRandomStringNumber(viper.GetInt("MaxRandToken"))
}
// generate id, timestamp and initialize access count for the new ShortLink
outLink = e.NewShortLink(outOrigin, outToken)
//store new link in database
bm.dalManager.PutLink(outLink)
log.WithFields(log.Fields{
"id": outLink.Id,
"token": outLink.Token,
"origin": outLink.Origin,
}).Info("New Short Link Created")
return outLink, nil
}
开发者ID:hellrider42,项目名称:ShortLinkRestApi,代码行数:63,代码来源:BusinessManager.go
示例17: main
/*
* Start the process
*
*/
func main() {
log.SetOutput(os.Stdout)
config_file := flag.String("config", "", "")
flag.Parse()
default_config_file := "config"
default_config_path := "./"
if *config_file != "" {
default_config_path, default_config_file = GetFileNameAndPath(*config_file)
}
viper.SetConfigName(default_config_file)
viper.AddConfigPath(default_config_path)
err := viper.ReadInConfig()
if err != nil {
log.Println("missing config file")
os.Exit(1)
}
config := Config{}
cols := strings.Split(viper.GetString("colums_hash"), ",")
config.columns_hash = arrStrToInt(&cols)
cols = strings.Split(viper.GetString("columns_content"), ",")
config.columns_content = arrStrToInt(&cols)
config.output = viper.GetString("outputdir")
config.deep_dirs = viper.GetInt("deepdirs")
config.delimiter = viper.GetString("delimiter")
config.iter = viper.GetInt("pbkdf2_iterations")
config.keylength = viper.GetInt("pbkdf2_keylength")
config.hash_dir = viper.GetBool("hash_dir")
if config.output == "" {
config.output = "./output/"
}
if config.iter == 0 {
config.iter = 100
}
if config.keylength == 0 {
config.keylength = 32
}
if config.delimiter == "" {
config.delimiter = ";"
}
log.Println("deleting " + config.output)
os.RemoveAll(config.output)
statify(viper.GetString("filename"), &config)
}
开发者ID:davidayalas,项目名称:staticdb,代码行数:60,代码来源:main.go
示例18: RunIcarus
func RunIcarus() {
// Run the solver as many times as the user desires.
fmt.Println("Solving", viper.GetInt("times"), "times")
for x := 0; x < viper.GetInt("times"); x++ {
solveMaze()
}
// Once we have solved the maze the required times, tell daedalus we are done
makeRequest("http://127.0.0.1:" + viper.GetString("port") + "/done")
}
开发者ID:captncraig,项目名称:gc6,代码行数:10,代码来源:icarus.go
示例19: CacheConfiguration
// CacheConfiguration computes and caches commonly-used constants and
// computed constants as package variables. Routines which were previously
// global have been embedded here to preserve the original abstraction.
func CacheConfiguration() (err error) {
// getLocalAddress returns the address:port the local peer is operating on. Affected by env:peer.addressAutoDetect
getLocalAddress := func() (peerAddress string, err error) {
if viper.GetBool("peer.addressAutoDetect") {
// Need to get the port from the peer.address setting, and append to the determined host IP
_, port, err := net.SplitHostPort(viper.GetString("peer.address"))
if err != nil {
err = fmt.Errorf("Error auto detecting Peer's address: %s", err)
return "", err
}
peerAddress = net.JoinHostPort(GetLocalIP(), port)
peerLogger.Infof("Auto detected peer address: %s", peerAddress)
} else {
peerAddress = viper.GetString("peer.address")
}
return
}
// getPeerEndpoint returns the PeerEndpoint for this Peer instance. Affected by env:peer.addressAutoDetect
getPeerEndpoint := func() (*pb.PeerEndpoint, error) {
var peerAddress string
var peerType pb.PeerEndpoint_Type
peerAddress, err := getLocalAddress()
if err != nil {
return nil, err
}
if viper.GetBool("peer.validator.enabled") {
peerType = pb.PeerEndpoint_VALIDATOR
} else {
peerType = pb.PeerEndpoint_NON_VALIDATOR
}
return &pb.PeerEndpoint{ID: &pb.PeerID{Name: viper.GetString("peer.id")}, Address: peerAddress, Type: peerType}, nil
}
localAddress, localAddressError = getLocalAddress()
peerEndpoint, peerEndpointError = getPeerEndpoint()
syncStateSnapshotChannelSize = viper.GetInt("peer.sync.state.snapshot.channelSize")
syncStateDeltasChannelSize = viper.GetInt("peer.sync.state.deltas.channelSize")
syncBlocksChannelSize = viper.GetInt("peer.sync.blocks.channelSize")
validatorEnabled = viper.GetBool("peer.validator.enabled")
securityEnabled = viper.GetBool("security.enabled")
configurationCached = true
if localAddressError != nil {
return localAddressError
} else if peerEndpointError != nil {
return peerEndpointError
}
return
}
开发者ID:yoshiharay,项目名称:fabric,代码行数:57,代码来源:config.go
示例20: NewCoordinatorImpl
// NewCoordinatorImpl constructs a coordinatorImpl
func NewCoordinatorImpl(stack PartialStack) Coordinator {
var err error
sts := &coordinatorImpl{}
sts.stack = stack
sts.RecoverDamage = viper.GetBool("statetransfer.recoverdamage")
sts.stateValid = true // Assume our starting state is correct unless told otherwise
sts.validBlockRanges = make([]*blockRange, 0)
sts.blockVerifyChunkSize = uint64(viper.GetInt("statetransfer.blocksperrequest"))
if sts.blockVerifyChunkSize == 0 {
panic(fmt.Errorf("Must set statetransfer.blocksperrequest to be nonzero"))
}
sts.blockSyncReq = make(chan *blockSyncReq)
sts.threadExit = make(chan struct{})
sts.DiscoveryThrottleTime = 1 * time.Second // TODO make this configurable
sts.BlockRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.singleblock"))
if err != nil {
panic(fmt.Errorf("Cannot parse statetransfer.timeout.singleblock timeout: %s", err))
}
sts.StateDeltaRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.singlestatedelta"))
if err != nil {
panic(fmt.Errorf("Cannot parse statetransfer.timeout.singlestatedelta timeout: %s", err))
}
sts.StateSnapshotRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.fullstate"))
if err != nil {
panic(fmt.Errorf("Cannot parse statetransfer.timeout.fullstate timeout: %s", err))
}
sts.maxStateDeltas = viper.GetInt("statetransfer.maxdeltas")
if sts.maxStateDeltas <= 0 {
panic(fmt.Errorf("sts.maxdeltas must be greater than 0"))
}
tmp := viper.GetInt("peer.sync.blocks.channelSize")
if tmp <= 0 {
panic(fmt.Errorf("peer.sync.blocks.channelSize must be greater than 0"))
}
sts.maxBlockRange = uint64(tmp)
tmp = viper.GetInt("peer.sync.state.deltas.channelSize")
if tmp <= 0 {
panic(fmt.Errorf("peer.sync.state.deltas.channelSize must be greater than 0"))
}
sts.maxStateDeltaRange = uint64(tmp)
return sts
}
开发者ID:yyhwhp,项目名称:fabric-1,代码行数:55,代码来源:statetransfer.go
注:本文中的github.com/spf13/viper.GetInt函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论