本文整理汇总了Golang中flag.Uint函数的典型用法代码示例。如果您正苦于以下问题:Golang Uint函数的具体用法?Golang Uint怎么用?Golang Uint使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Uint函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
laddr := flag.String("listen", ":8001", "listen address")
baddr := flag.String("backend", "127.0.0.1:1234", "backend address")
secret := flag.String("secret", "the answer to life, the universe and everything", "tunnel secret")
tunnels := flag.Uint("tunnels", 1, "low level tunnel count, 0 if work as server")
flag.Int64Var(&tunnel.Timeout, "timeout", 10, "tunnel read/write timeout")
flag.UintVar(&tunnel.LogLevel, "log", 1, "log level")
flag.Usage = usage
flag.Parse()
app := &tunnel.App{
Listen: *laddr,
Backend: *baddr,
Secret: *secret,
Tunnels: *tunnels,
}
err := app.Start()
if err != nil {
fmt.Fprintf(os.Stderr, "start failed:%s\n", err.Error())
return
}
go handleSignal(app)
app.Wait()
}
示例2: decodeRefArg
func decodeRefArg(name, typeName string) (interface{}, error) {
switch strings.ToLower(typeName) {
case "*bool":
newValue := flag.Bool(name, app.DefaultBoolValue, name)
return newValue, nil
case "bool":
newValue := flag.Bool(name, app.DefaultBoolValue, name)
return *newValue, nil
case "*string":
newValue := flag.String(name, app.DefaultStringValue, name)
return *newValue, nil
case "string":
newValue := flag.String(name, app.DefaultStringValue, name)
return *newValue, nil
case "*time.duration":
newValue := flag.Duration(name, app.DefaultDurationValue, name)
return *newValue, nil
case "time.duration":
newValue := flag.Duration(name, app.DefaultDurationValue, name)
return *newValue, nil
case "*float64":
newValue := flag.Float64(name, app.DefaultFloat64Value, name)
return *newValue, nil
case "float64":
newValue := flag.Float64(name, app.DefaultFloat64Value, name)
return *newValue, nil
case "*int":
newValue := flag.Int(name, app.DefaultIntValue, name)
return *newValue, nil
case "int":
newValue := flag.Int(name, app.DefaultIntValue, name)
return *newValue, nil
case "*int64":
newValue := flag.Int64(name, app.DefaultInt64Value, name)
return *newValue, nil
case "int64":
newValue := flag.Int64(name, app.DefaultInt64Value, name)
return *newValue, nil
case "*uint":
newValue := flag.Uint(name, app.DefaultUIntValue, name)
return *newValue, nil
case "uint":
newValue := flag.Uint(name, app.DefaultUIntValue, name)
return *newValue, nil
case "*uint64":
newValue := flag.Uint64(name, app.DefaultUInt64Value, name)
return *newValue, nil
case "uint64":
newValue := flag.Uint64(name, app.DefaultUInt64Value, name)
return *newValue, nil
}
return nil, fmt.Errorf("unknow type %s for argument %s", typeName, name)
}
示例3: handleFlags
func handleFlags() (*CliOptions, bool) {
flag.Usage = Usage
_ = flag.String("serveraddr", "127.0.0.1", "Server address to listen") // ignored
serverPort := flag.Uint("port", 9000, "Port to listen")
portLayerAddr := flag.String("port-layer-addr", "127.0.0.1", "Port layer server address")
portLayerPort := flag.Uint("port-layer-port", 9001, "Port Layer server port")
debug := flag.Bool("debug", false, "Enable debuglevel logging")
flag.Parse()
// load the vch config
src, err := extraconfig.GuestInfoSource()
if err != nil {
log.Fatalf("Unable to load configuration from guestinfo: %s", err)
}
extraconfig.Decode(src, &vchConfig)
if *debug || vchConfig.Diagnostics.DebugLevel > 0 {
log.SetLevel(log.DebugLevel)
}
cli := &CliOptions{
serverPort: *serverPort,
portLayerAddr: fmt.Sprintf("%s:%d", *portLayerAddr, *portLayerPort),
proto: "tcp",
}
return cli, true
}
示例4: handleFlags
func handleFlags() (*CliOptions, bool) {
flag.Usage = Usage
enableTLS := flag.Bool("TLS", false, "Use TLS; implied by --tlsverify")
verifyTLS := flag.Bool("tlsverify", false, "Use TLS and verify the remote")
cafile := flag.String("tls-ca-certificate", "", "Trust certs signed only by this CA")
certfile := flag.String("tls-certificate", "", "Path to TLS certificate file")
keyfile := flag.String("tls-key", "", "Path to TLS Key file")
serverAddr := flag.String("serveraddr", "127.0.0.1", "Server address to listen")
serverPort := flag.Uint("port", 9000, "Port to listen")
portLayerAddr := flag.String("port-layer-addr", "127.0.0.1", "Port layer server address")
portLayerPort := flag.Uint("port-layer-port", 9001, "Port Layer server port")
debug := flag.Bool("debug", false, "Enable debuglevel logging")
flag.Parse()
if *enableTLS && (len(*certfile) == 0 || len(*keyfile) == 0) {
fmt.Fprintf(os.Stderr, "TLS requested, but tls-certificate and tls-key were all not specified\n")
return nil, false
}
if *verifyTLS {
*enableTLS = true
if len(*certfile) == 0 || len(*keyfile) == 0 || len(*cafile) == 0 {
fmt.Fprintf(os.Stderr, "tlsverfiy requested, but tls-ca-certificate, tls-certificate, tls-key were all not specified\n")
return nil, false
}
}
cli := &CliOptions{
enableTLS: *enableTLS,
verifyTLS: *verifyTLS,
cafile: *cafile,
certfile: *certfile,
keyfile: *keyfile,
serverAddr: *serverAddr,
serverPort: *serverPort,
fullserver: fmt.Sprintf("%s:%d", *serverAddr, *serverPort),
portLayerAddr: fmt.Sprintf("%s:%d", *portLayerAddr, *portLayerPort),
proto: "tcp",
}
// load the vch config
src, err := extraconfig.GuestInfoSource()
if err != nil {
log.Errorf("Unable to load configuration from guestinfo")
}
extraconfig.Decode(src, &vchConfig)
if *debug || vchConfig.Diagnostics.DebugLevel > 0 {
log.SetLevel(log.DebugLevel)
}
return cli, true
}
示例5: main
func main() {
// Define and parse flags.
id := flag.Uint("id", 0, "Set the client node ID to connect to.")
rate = flag.Uint("rate", 0, "Sets the maximum messages per second.")
flag.Parse()
// Validate flags.
if *id == 0 || *id > 0xFFFF {
log.Fatal("Invalid node ID specified.")
}
// Load configuration from config file.
loadConfig()
fmt.Printf("Loaded configuration, ID to connect to is %d.\n", *id)
conn, err := connect.TestDial(uint16(*id))
if err != nil {
log.Fatal(err)
}
var msg cliproto_up.Authenticate
msg.Username = new(string)
msg.Password = new(string)
msg.SessionId = new(uint64)
*msg.Username = "msgsource"
*msg.Password = "msgsource"
conn.SendProto(2, &msg)
for {
respMsg, ok := <-conn.Received
if !ok {
log.Fatal("connection error")
}
switch *respMsg.MsgType {
case 2:
conn.Close()
log.Fatal("auth failed")
case 3:
log.Print("authenticated, follow msgsink...")
var followMsg cliproto_up.FollowUsername
followMsg.Username = new(string)
*followMsg.Username = "msgsink"
conn.SendProto(3, &followMsg)
case 4:
log.Fatal("follow failed")
case 6:
handleData(respMsg.Content)
case 7:
log.Print("following msgsink, sending msgs...")
go sendMessages(conn)
}
}
}
示例6: main
func main() {
dryRun := flag.Bool("dryRun", true, "Whether to do a dry run.")
sleep := flag.Duration("sleep", 60*time.Second, "How long to sleep between batches.")
batchSize := flag.Uint("batchSize", 1000, "Number of certificates to process between sleeps.")
numBatches := flag.Uint("numBatches", 999999, "Stop processing after N batches.")
type config struct {
NotAfterBackFiller struct {
cmd.DBConfig
}
Statsd cmd.StatsdConfig
Syslog cmd.SyslogConfig
}
configFile := flag.String("config", "", "File containing a JSON config.")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "%s\n\n", usageIntro)
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if *configFile == "" {
flag.Usage()
os.Exit(1)
}
configData, err := ioutil.ReadFile(*configFile)
cmd.FailOnError(err, fmt.Sprintf("Reading %q", *configFile))
var cfg config
err = json.Unmarshal(configData, &cfg)
cmd.FailOnError(err, "Unmarshaling config")
stats, log := cmd.StatsAndLogging(cfg.Statsd, cfg.Syslog)
defer log.AuditPanic()
dbURL, err := cfg.NotAfterBackFiller.DBConfig.URL()
cmd.FailOnError(err, "Couldn't load DB URL")
dbMap, err := sa.NewDbMap(dbURL, 10)
cmd.FailOnError(err, "Could not connect to database")
go sa.ReportDbConnCount(dbMap, metrics.NewStatsdScope(stats, "NotAfterBackfiller"))
b := backfiller{
dbMap: dbMap,
log: log,
clk: cmd.Clock(),
dryRun: *dryRun,
batchSize: *batchSize,
numBatches: *numBatches,
sleep: *sleep,
}
err = b.processForever()
cmd.FailOnError(err, "Could not process certificate batches")
}
示例7: Main
func Main() error {
messageTimeout := flag.Duration("message_timeout", 2*time.Minute, "timeout for one message to be proxied")
clientIdleTimeout := flag.Duration("client_idle_timeout", 60*time.Minute, "idle timeout for client connections")
serverIdleTimeout := flag.Duration("server_idle_timeout", 1*time.Hour, "idle timeout for server connections")
serverClosePoolSize := flag.Uint("server_close_pool_size", 100, "number of goroutines that will handle closing server connections")
getLastErrorTimeout := flag.Duration("get_last_error_timeout", time.Minute, "timeout for getLastError pinning")
maxPerClientConnections := flag.Uint("max_per_client_connections", 100, "maximum number of connections per client")
maxConnections := flag.Uint("max_connections", 100, "maximum number of connections per mongo")
portStart := flag.Int("port_start", 6000, "start of port range")
portEnd := flag.Int("port_end", 6010, "end of port range")
addrs := flag.String("addrs", "localhost:27017", "comma separated list of mongo addresses")
flag.Parse()
replicaSet := dvara.ReplicaSet{
Addrs: *addrs,
PortStart: *portStart,
PortEnd: *portEnd,
MessageTimeout: *messageTimeout,
ClientIdleTimeout: *clientIdleTimeout,
ServerIdleTimeout: *serverIdleTimeout,
ServerClosePoolSize: *serverClosePoolSize,
GetLastErrorTimeout: *getLastErrorTimeout,
MaxConnections: *maxConnections,
MaxPerClientConnections: *maxPerClientConnections,
}
var statsClient stats.HookClient
var log stdLogger
var graph inject.Graph
err := graph.Provide(
&inject.Object{Value: &log},
&inject.Object{Value: &replicaSet},
&inject.Object{Value: &statsClient},
)
if err != nil {
return err
}
if err := graph.Populate(); err != nil {
return err
}
objects := graph.Objects()
if err := startstop.Start(objects, &log); err != nil {
return err
}
defer startstop.Stop(objects, &log)
ch := make(chan os.Signal, 2)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT)
<-ch
signal.Stop(ch)
return nil
}
示例8: main
func main() {
defer trace("gperfect")()
perPtr := flag.Uint64("number", 0, "Perfect number to find")
coreCountPtr := flag.Uint("numCores", 8, "Number of cores to use when calculating random perfect numbers")
numRandPtr := flag.Uint("numRandom", 100, "Number of random perfect numbers to look for. Omit for continuous calculations")
flag.Parse()
if *perPtr > 0 {
calcPerfect(*perPtr, *coreCountPtr)
} else {
calcRandPerfects(coreCountPtr, numRandPtr)
}
}
示例9: main
func main() {
var isWrite bool
bus := flag.Uint("bus", 0, "bus number, [0 : 255]")
dev := flag.Uint("dev", 0, "device number, [0 : 63]")
function := flag.Uint("function", 0, "function number, [0 : 7]")
offset := flag.Uint("offset", 0, "offset, [0 : 255] and 4 byte aligned")
flag.Usage = usage
flag.Parse()
// Check parameters
if *bus >= PciBusLimit || *dev >= PciDevLimit ||
*function >= PciFuncLimit ||
*offset >= PciRegLimit || *offset&0x03 != 0 {
usage()
}
switch flag.NArg() {
case 0:
isWrite = false
case 1:
isWrite = true
default:
usage()
}
busVal := uint32(*bus)
devVal := uint32(*dev)
funcVal := uint32(*function)
offsetVal := uint32(*offset)
ioLevel(3)
defer ioLevel(0)
if isWrite {
value, err := strconv.ParseUint(flag.Arg(0), 0, 32)
if err != nil {
log.Fatal(err)
}
pciWriteConfReg(busVal, devVal, funcVal, offsetVal,
uint32(value))
}
data := pciReadConfReg(busVal, devVal, funcVal, offsetVal)
fmt.Printf("[%02X:%02X.%X-%02X] = %08x\n",
busVal, devVal, funcVal, offsetVal, data)
}
示例10: main
func main() {
var (
brokerName = flag.String("broker", brokers[0], brokerList())
brokerPort = flag.String("broker-port", defaultBrokerPort, "host machine broker port")
dockerHost = flag.String("docker-host", defaultHost, "host machine (or VM) running Docker")
brokerdHost = flag.String("host", defaultDaemonHost, "machine running broker daemon")
peerHosts = flag.String("peer-hosts", defaultDaemonHost, "comma-separated list of machines to run peers")
producers = flag.Uint("producers", defaultNumProducers, "number of producers per host")
consumers = flag.Uint("consumers", defaultNumConsumers, "number of consumers per host")
numMessages = flag.Uint("num-messages", defaultNumMessages, "number of messages to send from each producer")
messageSize = flag.Uint64("message-size", defaultMessageSize, "size of each message in bytes")
startupSleep = flag.Uint("startup-sleep", defaultStartupSleep, "seconds to wait after broker start before benchmarking")
daemonTimeout = flag.Uint("daemon-timeout", defaultDaemonTimeout, "seconds to wait for daemon before timing out")
dockerExtras = flag.String("docker-extra", "", "extra args to pass to `docker run'")
)
flag.Parse()
peers := strings.Split(*peerHosts, ",")
client, err := broker.NewClient(&broker.Benchmark{
BrokerdHost: *brokerdHost,
BrokerName: *brokerName,
BrokerHost: *dockerHost,
BrokerPort: *brokerPort,
PeerHosts: peers,
NumMessages: *numMessages,
MessageSize: *messageSize,
Publishers: *producers,
Subscribers: *consumers,
StartupSleep: *startupSleep,
DaemonTimeout: *daemonTimeout,
DockerExtras: *dockerExtras,
})
if err != nil {
fmt.Println("Failed to connect to flotilla:", err)
os.Exit(1)
}
start := time.Now()
results, err := runBenchmark(client)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
elapsed := time.Since(start)
printSummary(client.Benchmark, elapsed)
printResults(results)
}
示例11: main
func main() {
// Parse arguments
verbose := flag.Bool("v", false, "Print verbose output to stdout")
startColumn := flag.Uint("b", 0, "Fist column from the left of the table to unmerge")
endColumn := flag.Uint("e", 0, "Last column from left of table to unmerge")
inputDelimiter := flag.String("id", `\s*:\s*`, "Feild input delimiter (Golang regexp)")
outputDelimiter := flag.String("od", "\t:\t", "Feild output delimiter")
flag.Parse()
// Open stdin
ibuf := bufio.NewReader(os.Stdin)
err := worker(ibuf, *startColumn, *endColumn, *inputDelimiter, *outputDelimiter, *verbose, os.Stdout)
if err != nil {
log.Fatal(err)
}
}
示例12: main
func main() {
var size = flag.Uint("size", 0, "New size of the disk in GB")
// Allow the same ID types as in disk_remove.go
var reMajMin = regexp.MustCompile(`^\d+:\d+$`)
var reMin = regexp.MustCompile(`^\d+$`)
var id string
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [options] <Server-Name> <Disk-ID>\n", path.Base(os.Args[0]))
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() != 2 || *size == 0 {
flag.Usage()
os.Exit(1)
} else if reMajMin.MatchString(flag.Arg(1)) {
id = flag.Arg(1)
} else if reMin.MatchString(flag.Arg(1)) {
id = fmt.Sprintf("0:%s", flag.Arg(1))
} else {
exit.Errorf("invalid disk ID %q", flag.Arg(1))
}
client, err := clcv2.NewCLIClient()
if err != nil {
exit.Fatal(err.Error())
}
server, err := client.GetServer(flag.Arg(0))
if err != nil {
exit.Fatalf("failed to list details of server %q: %s", flag.Arg(0), err)
}
disks := make([]clcv2.ServerAdditionalDisk, len(server.Details.Disks))
for i := range server.Details.Disks {
disks[i] = clcv2.ServerAdditionalDisk{
Id: server.Details.Disks[i].Id,
SizeGB: server.Details.Disks[i].SizeGB,
}
if disks[i].Id == id {
// The API does not allow to reduce the size of an existing disk.
if uint32(*size) <= disks[i].SizeGB {
fmt.Printf("Disk %s size is already at %d GB.\n", id, disks[i].SizeGB)
os.Exit(0)
}
fmt.Printf("Changing disk %s size from %d to %d GB ...\n",
id, disks[i].SizeGB, *size)
disks[i].SizeGB = uint32(*size)
}
}
reqID, err := client.ServerSetDisks(flag.Arg(0), disks)
if err != nil {
exit.Fatalf("failed to update the disk configuration on %q: %s", flag.Arg(0), err)
}
log.Printf("Status Id for resizing the disk on %s: %s", flag.Arg(0), reqID)
client.PollStatus(reqID, 10*time.Second)
}
示例13: main
func main() {
var shops golib.StringSlice
parallel_orders := flag.Uint("orders", 20, "Number of open orders running at the same time")
bank := flag.String("bank", "localhost:9001", "Bank endpoint")
timeout := flag.Duration("timeout", 0, "Timeout for automatically stopping load generation")
flag.Var(&shops, "shop", "Shop endpoint(s)")
flag.Parse()
if len(shops) == 0 {
log.Fatalln("Specify at least one -shop")
}
golib.ConfigureOpenFilesLimit()
orders := OrderPool{
ParallelOrders: *parallel_orders,
Bank: *bank,
Shops: shops,
User: "Load",
}
orders.Start()
onInterrupt(orders.Terminate)
if *timeout > 0 {
services.L.Warnf("Terminating automatically after %v", timeout)
time.AfterFunc(*timeout,
func() {
services.L.Warnf("Timer of %v expired. Terminating...", timeout)
orders.Terminate()
})
}
orders.Wait()
orders.PrintStats()
}
示例14: main
func main() {
var listenAPI = flag.String("http", "0.0.0.0:9381", "http port to listen on")
var listenSMTP = flag.String("smtp", "0.0.0.0:9380", "smtp port to listen on")
var closeFirst = flag.Uint("closeFirst", 0, "close first n connections after MAIL for reconnection tests")
flag.Parse()
l, err := net.Listen("tcp", *listenSMTP)
if err != nil {
log.Fatalln("Couldn't bind %q for SMTP", *listenSMTP, err)
}
defer l.Close()
srv := mailSrv{
closeFirst: *closeFirst,
}
srv.setupHTTP(http.DefaultServeMux)
go func() {
err := http.ListenAndServe(*listenAPI, http.DefaultServeMux)
if err != nil {
log.Fatalln("Couldn't start HTTP server", err)
}
}()
err = srv.serveSMTP(l)
if err != nil {
log.Fatalln(err, "Failed to accept connection")
}
}
示例15: main
func main() {
launchTimeout :=
flag.Uint("launch-timeout", 240,
"Seconds to retry launching an etcd instance for before giving up. "+
"This should be long enough for a port occupied by a killed process "+
"to be vacated.")
flag.Parse()
log.Infoln("Starting etcd Executor")
dconfig := executor.DriverConfig{
Executor: etcdexecutor.New(
time.Duration(*launchTimeout) * time.Second,
),
}
driver, err := executor.NewMesosExecutorDriver(dconfig)
if err != nil {
log.Infoln("Unable to create an ExecutorDriver ", err.Error())
}
_, err = driver.Start()
if err != nil {
log.Infoln("Got error:", err)
return
}
log.Infoln("Executor process has started and running.")
driver.Join()
}