예제 #1
1
파일: httpserver.go 프로젝트: runcom/gossl
func main() {
	certpath := flag.String("cert", "", "The path to a PEM certificate")
	keypath := flag.String("key", "", "The path to a PEM key")
	flag.Parse()
	if len(*certpath) == 0 || len(*keypath) == 0 {
		flag.PrintDefaults()
		return
	}
	ctx := gossl.NewContext(gossl.SSLv3Method())
	ctx.SetOptions(gossl.OpNoCompression)
	err := ctx.UsePrivateKeyFile(*keypath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	ctx.UseCertificateFile(*certpath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	l, err := net.Listen("tcp", ":8000")
	if err != nil {
		panic(err)
	}
	l, err = gossl.NewListener(l, ctx)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %q\n", html.EscapeString(r.URL.Path))
	})
	http.Serve(l, nil)

}
예제 #2
0
파일: main.go 프로젝트: tcolgate/test
func main() {
	flag.Parse()

	grpc.EnableTracing = true

	flag.Parse()
	lis, err := net.Listen("tcp", *port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	grpcServer := grpc.NewServer()

	var downstreamClients []pb.PingClient
	for _, d := range strings.Split(*downstreams, ",") {
		if d == "" {
			continue
		}
		log.Println(d)
		conn, err := grpc.Dial(d, grpc.WithBlock())
		if err != nil {
			log.Fatalf("In here " + err.Error())
		}
		defer conn.Close()

		downstreamClients = append(downstreamClients, pb.NewPingClient(conn))
	}
	pb.RegisterPingServer(grpcServer, &pingServer{downstreams: downstreamClients})

	go grpcServer.Serve(lis)

	log.Fatal(http.ListenAndServe(*httpPort, nil))
}
예제 #3
0
파일: doozer.go 프로젝트: musicglue/doozer
func main() {
	if e := os.Getenv("DOOZER_URI"); e != "" {
		*uri = e
	}

	if e := os.Getenv("DOOZER_BOOT_URI"); e != "" {
		*buri = e
	}

	flag.Usage = usage
	flag.Parse()

	if *showHelp {
		usage()
		return
	}

	if *showVersion {
		fmt.Println("doozer", version)
		return
	}

	if flag.NArg() < 1 {
		fmt.Fprintf(os.Stderr, "%s: missing command\n", os.Args[0])
		usage()
		os.Exit(127)
	}

	cmd := flag.Arg(0)

	c, ok := cmds[cmd]
	if !ok {
		fmt.Fprintln(os.Stderr, "Unknown command:", cmd)
		usage()
		os.Exit(127)
	}

	os.Args = flag.Args()
	flag.Parse()

	if *showHelp {
		help(cmd)
		return
	}

	args := flag.Args()
	ft := reflect.TypeOf(c.f)
	if len(args) != ft.NumIn() {
		fmt.Fprintf(os.Stderr, "%s: wrong number of arguments\n", cmd)
		help(cmd)
		os.Exit(127)
	}

	vals := make([]reflect.Value, len(args))
	for i, s := range args {
		vals[i] = reflect.ValueOf(s)
	}
	fv := reflect.ValueOf(c.f)
	fv.Call(vals)
}
예제 #4
0
파일: main.go 프로젝트: arvinkulagin/beeper
func main() {
	logger := log.NewLogger()
	cfg := config.Default()
	flag.StringVar(&cfg.WSAddress, "ws", cfg.WSAddress, "Websocket address")
	flag.StringVar(&cfg.RESTAddress, "rest", cfg.RESTAddress, "REST address")
	flag.StringVar(&cfg.Origin, "o", cfg.Origin, "Origin URL")
	file := flag.String("config", "", "Config file")
	flag.Parse()
	if *file != "" {
		err := config.FromFile(*file, &cfg)
		if err != nil {
			logger.Err.Fatal(err)
		}
		flag.Parse()
	}
	broker := pubsub.NewBroker()
	go func() {
		wsRouter := mux.NewRouter()
		wsRouter.Handle("/{id}", handlers.WSHandler{Broker: broker, Config: cfg, Logger: logger})
		logger.Out.Println("Listening websockets on", cfg.WSAddress)
		logger.Err.Fatal(http.ListenAndServe(cfg.WSAddress, wsRouter))
	}()
	go func() {
		restRouter := mux.NewRouter()
		restRouter.Handle("/topic", handlers.List{Broker: broker, Logger: logger}).Methods("GET")
		restRouter.Handle("/topic", handlers.Add{Broker: broker, Logger: logger}).Methods("POST")
		restRouter.Handle("/topic/{id}", handlers.Pub{Broker: broker, Logger: logger}).Methods("POST")
		restRouter.Handle("/topic/{id}", handlers.Del{Broker: broker, Logger: logger}).Methods("DELETE")
		restRouter.Handle("/ping", handlers.Ping{Logger: logger}).Methods("GET")
		logger.Out.Println("Listening REST on", cfg.RESTAddress)
		logger.Err.Fatal(http.ListenAndServe(cfg.RESTAddress, restRouter))
	}()
	wait := make(chan struct{})
	<-wait
}
예제 #5
0
파일: main.go 프로젝트: kshvakov/thunder
func main() {
	var action string

	// rewrite arguments so that we can support multiple "actions" in a single binary
	newArgs := make([]string, 0, len(os.Args))
	for i, arg := range os.Args {
		if i > 0 && arg[0] != '-' && action == "" {
			action = arg
			continue
		}

		newArgs = append(newArgs, arg)
	}
	os.Args = newArgs

	if action == "" {
		fmt.Fprintln(os.Stderr, "Error: action was not specified")
		dieWithUsage()
	}

	if action == ACTION_LOGS_COLLECTOR {
		logscol.InitFlags()
		flag.Parse()
		logscol.Run()
		return
	} else if action == ACTION_LOGS_PROCESSOR {
		logsproc.InitFlags()
		flag.Parse()
		logsproc.Run()
		return
	}

	dieWithUsage()
}
예제 #6
0
func main() {
	flag.Usage = help

	cmd := "help"
	switch av0 := path.Base(os.Args[0]); av0 {
	case "tao_run", "tao_list", "tao_stop", "tao_kill":
		cmd = av0[4:]
		flag.Parse()
	default:
		// Get options before the command verb
		flag.Parse()
		// Get command verb
		if flag.NArg() > 0 {
			cmd = flag.Arg(0)
		}
		// Get options after the command verb
		if flag.NArg() > 1 {
			flag.CommandLine.Parse(flag.Args()[1:])
		}
	}

	sockPath := path.Join(hostPath(), "admin_socket")
	conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: sockPath, Net: "unix"})
	options.FailIf(err, "Can't connect to host admin socket")
	defer conn.Close()

	client := tao.NewLinuxHostAdminClient(conn)
	switch cmd {
	case "help":
		help()
	case "run":
		runHosted(&client, flag.Args())
	case "stop":
		for _, s := range flag.Args() {
			var subprin auth.SubPrin
			_, err := fmt.Sscanf(s, "%v", &subprin)
			options.FailIf(err, "Not a subprin: %s", s)
			err = client.StopHostedProgram(subprin)
			options.FailIf(err, "Could not stop %s", s)
		}
	case "kill":
		for _, s := range flag.Args() {
			var subprin auth.SubPrin
			options.FailIf(err, "Not a subprin: %s", s)
			err = client.KillHostedProgram(subprin)
			options.FailIf(err, "Could not kill %s", s)
		}
	case "list":
		names, pids, err := client.ListHostedPrograms()
		options.FailIf(err, "Can't list hosted programs")
		for i, p := range pids {
			fmt.Printf("pid=%d subprin=%v\n", p, names[i])
		}
		fmt.Printf("%d hosted programs\n", len(pids))
	default:
		options.Usage("Unrecognized command: %s", cmd)
	}

	return
}
예제 #7
0
func main() {
	var listenErr chan error
	flag.Var(&plines, "c", "Path to config, may be repeated")
	flag.Parse()

	if len(plines) == 0 {
		log.Fatal("No configs provided")
	}

	if *prometheusAddr != "" {
		if *loop == 0 {
			log.Fatal("Can only expose metrics in daemon mode")
		}
		http.Handle("/metrics", prometheus.Handler())
		go http.ListenAndServe(*prometheusAddr, nil)
	}
	if *debugEndpoint != "" {
		go func() {
			listenErr <- http.ListenAndServe(*debugEndpoint, nil)

		}()
	}

	for {
		for _, file := range plines {
			log.Print("# Running ", file)
			backupsTotal.WithLabelValues(file).Inc()
			pipe, err := pipeline.New(file)
			if err != nil {
				log.Printf("ERROR loading %s: %s", file, err)
				backupsFailed.WithLabelValues(file).Inc()
				continue
			}
			begin := time.Now()
			bytesWritten, err := pipe.Run()
			if err != nil {
				log.Printf("ERROR running %s: %s", file, err)
				backupsFailed.WithLabelValues(file).Inc()
				continue
			}
			backupSize.WithLabelValues(file).Set(float64(bytesWritten))

			now := time.Now()
			backupSeen.WithLabelValues(file).Set(float64(now.Unix()))
			backupDuration.WithLabelValues(file).Set(now.Sub(begin).Seconds())
		}
		if *loop == 0 {
			break
		}
		plines = pipelines{}
		log.Print("Sleeping for ", *loop)
		time.Sleep(*loop)
		flag.Parse() // We can do that nicer..
	}
	if *debugEndpoint != "" {
		log.Print("Debugging enabled, keep listening for debugging")
		log.Print(<-listenErr)
	}
}
예제 #8
0
파일: main.go 프로젝트: jyzhe/beehive
func main() {
	flag.Parse()

	if *k%2 != 0 || *from < 1 || *to < 1 || *k < *from || *k < *to {
		log.Fatal("Invalid parameters", *from, *to, *k)
	}

	flag.Parse()
	if *cpuProfile != "" {
		f, err := os.Create(*cpuProfile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	routing.InstallRouting(*epoc)

	chrono := bh.NewApp("Chrono")
	ch := make(chan bool, 1024)
	cnt := 0
	rcvF := func(msg bh.Msg, ctx bh.RcvContext) error {
		if cnt++; cnt%1024 == 0 {
			ch <- true
		}
		return nil
	}
	mapF := func(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {
		return ctx.LocalMappedCells()
	}
	chrono.HandleFunc(routing.Advertisement{}, mapF, rcvF)

	start := time.Now()
	for p := *from; p <= *to; p++ {
		go func(p int) {
			if err := emitPod(p, *k); err != nil {
				panic(err)
			}
		}(p)
	}
	go func() {
		bh.Start()
		close(ch)
	}()

	finish := time.Now()
	for {
		select {
		case _, ok := <-ch:
			if !ok {
				return
			}
			finish = time.Now()
		case <-time.After(*idleTimeout):
			log.Printf("Took %v (%v-%v)", finish.Sub(start), start, finish)
		}
	}
}
예제 #9
0
func InitTests(startIndexor bool) {
	if !hasStartedTesting {
		flag.Parse()
		hasStartedTesting = true
		flag.Parse()
		log.SetFlags(log.Ltime | log.Lshortfile)
		api.Domain = *eshost
	}
}
예제 #10
0
func main() {

	flag.Parse()
	args := flag.Args()
	fmt.Fprintf(os.Stderr, "\n")

	availableCommands := "Available commands:\n\n maketorrent\n info"

	if len(args) > 0 {
		switch args[0] {
		case "maketorrent":
			name := flag.String("name", "", "Torrent name, defaults to [file]+.torrent")
			announce := flag.String("announce", "udp://tracker.publicbt.com:80", "Tracker url")
			announceList := flag.String("announceList", "", "Comma seperated tracker urls")
			comment := flag.String("comment", "", "Optional comment")
			createdBy := flag.String("createdBy", "Tulva", "Author")
			encoding := flag.String("encoding", "UTF-8", "Encoding")

			flag.Parse()
			args = flag.Args()

			if len(args) == 1 {
				fmt.Fprintf(os.Stderr, "Usage: maketorrent [options] File\n\n")
				flag.PrintDefaults()
			} else if len(args) == 2 {
				clf := &CLFlags{
					Name:         *name,
					Announce:     *announce,
					AnnounceList: *announceList,
					Comment:      *comment,
					CreatedBy:    *createdBy,
					Encoding:     *encoding,
				}
				t := MakeTorrentFile(args[1], clf)
				fmt.Fprintf(os.Stderr, "Made torrent File: %s", t.Name())
			}
		case "info":
			name := flag.Bool("name", true, "Torrent name")
			if len(args) == 1 {
				fmt.Fprintf(os.Stderr, "Usage: info [options] File\n\n")
				flag.PrintDefaults()
			} else if len(args) == 2 {
				metaInfo := TorrentInfo(args[1])
				fmt.Fprintf(os.Stderr, "Info:\n\n")
				if *name {
					fmt.Fprintf(os.Stderr, "\tName: %s", metaInfo.info.name)
				}
			}
		default:
			fmt.Fprintf(os.Stderr, availableCommands)
		}
	} else {
		fmt.Fprintf(os.Stderr, availableCommands)
	}
	fmt.Fprintf(os.Stderr, "\n\n")
}
예제 #11
0
func main() {
	// Define our commandline flags:
	fs := flag.String("fs", ".", "Root directory of served files and templates")
	xrGifArg := flag.String("xrg", "", "X-Accel-Redirect header prefix for serving images or blank to disable")
	xrThumbArg := flag.String("xrt", "", "X-Accel-Redirect header prefix for serving thumbnails or blank to disable")

	fl_listen_uri := flag.String("l", "tcp://0.0.0.0:8080", "listen URI (schemes available are tcp, unix)")
	flag.Parse()

	// Parse all the URIs:
	listen_addr, err := base.ParseListenable(*fl_listen_uri)
	base.PanicIf(err)

	// Parse the flags and set values:
	flag.Parse()

	// Make directories we need:
	base_folder = base.CanonicalPath(path.Clean(*fs))
	os.MkdirAll(store_folder(), 0775)
	os.MkdirAll(thumb_folder(), 0775)
	os.MkdirAll(tmp_folder(), 0775)

	xrGif = *xrGifArg
	xrThumb = *xrThumbArg

	// Create/update the DB schema if needed:
	api, err := NewAPI()
	if err != nil {
		log.Fatal(err)
		return
	}
	api.Close()

	// Watch the html templates for changes and reload them:
	_, cleanup, err := web.WatchTemplates("ui", html_path(), "*.html", nil, &uiTmpl)
	if err != nil {
		log.Println(err)
		return
	}
	defer cleanup()

	// Start profiler:
	go func() {
		log.Println(http.ListenAndServe("localhost:6060", nil))
	}()

	// Start the server:
	_, err = base.ServeMain(listen_addr, func(l net.Listener) error {
		return http.Serve(l, web.ReportErrors(web.Log(web.DefaultErrorLog, web.ErrorHandlerFunc(requestHandler))))
	})
	if err != nil {
		log.Println(err)
		return
	}
}
예제 #12
0
파일: pat_config.go 프로젝트: popeye17/pat
func (config *Config) Parse() error {
	flag.Parse()
	if config.Config != "" {
		err := config.parseConfigParamFile()
		if err != nil {
			return err
		}
	}
	flag.Parse()
	return nil
}
예제 #13
0
파일: main.go 프로젝트: CodeJuan/deis
func init() {
	flag.StringVar(&storage.LogRoot, "log-root", "/data/logs", "log path to store logs")
	// Support a legacy behavior that that allows default drain uri to be specified using a drain-uri
	// flag.
	flag.StringVar(&configurer.DefaultDrainURI, "drain-uri", "", "default drainURI, once set in etcd, this has no effect.")
	flag.Parse()
	// Set the default value for this AFTER the proper value of *publishInterval has been
	// established, since publishTTL should be twice the publishInterval by default.
	flag.IntVar(&publishTTL, "publish-ttl", *publishInterval*2, "publish TTL in seconds")
	// Now reparse flags in case the default publishTTL is overriden by a flag.
	flag.Parse()
}
예제 #14
0
파일: main.go 프로젝트: Espresson/xlsx2csv
func main() {
	flag.Parse()
	if len(os.Args) < 3 {
		flag.PrintDefaults()
		return
	}
	flag.Parse()
	printer := func(s string) { fmt.Printf("%s", s) }
	if err := generateCSVFromXLSXFile(*xlsxPath, *sheetIndex, printer); err != nil {
		fmt.Println(err)
	}
}
예제 #15
0
파일: doozer.go 프로젝트: kr/doozer
func main() {
	flag.Usage = Usage
	flag.Parse()

	if *showHelp {
		Usage()
		return
	}

	if *showVersion {
		fmt.Println("doozer", doozer.Version)
		return
	}

	if flag.NArg() < 1 {
		fmt.Fprintf(os.Stderr, "%s: missing command\n", os.Args[0])
		Usage()
		os.Exit(127)
	}

	cmd := flag.Arg(0)

	c, ok := cmds[cmd]
	if !ok {
		fmt.Fprintln(os.Stderr, "Unknown command:", cmd)
		Usage()
		os.Exit(127)
	}

	os.Args = flag.Args()
	flag.Parse()

	if *showHelp {
		help(cmd)
		return
	}

	args := flag.Args()
	ft := reflect.Typeof(c.f).(*reflect.FuncType)
	if len(args) != ft.NumIn() {
		fmt.Fprintf(os.Stderr, "%s: wrong number of arguments\n", cmd)
		help(cmd)
		os.Exit(127)
	}

	vals := make([]reflect.Value, len(args))
	for i, s := range args {
		vals[i] = reflect.NewValue(s)
	}
	fv := reflect.NewValue(c.f).(*reflect.FuncValue)
	fv.Call(vals)
}
예제 #16
0
파일: main.go 프로젝트: tealeg/csv2xlsx
func main() {
	flag.Parse()
	if len(os.Args) < 3 {
		usage()
		return
	}
	flag.Parse()
	err := generateXLSXFromCSV(*csvPath, *xlsxPath, *delimiter)
	if err != nil {
		fmt.Printf(err.Error())
		return
	}
}
예제 #17
0
파일: main.go 프로젝트: hlife/xlsx2csv
func main() {
	flag.Parse()
	var error error
	if len(os.Args) < 3 {
		usage()
		return
	}
	flag.Parse()
	error = generateCSVFromXLSXFile(*xlsxPath, *sheetIndex, func(s string) { fmt.Printf("%s", s) })
	if error != nil {
		fmt.Printf(error.Error())
		return
	}
}
예제 #18
0
파일: main.go 프로젝트: c4e8ece0/goAdaGrad
func main() {
	var loop int
	var file string
	var mode string
	var model string
	var lambda float64
	var verbose bool
	flag.IntVar(&loop, "l", 10, "number of iterations")
	flag.Float64Var(&lambda, "c", 0.1, "regularization parameter")
	flag.StringVar(&file, "f", "", "data file")
	flag.StringVar(&mode, "m", "", "mode {learn, test}")
	flag.StringVar(&model, "w", "", "model file")
	flag.BoolVar(&verbose, "v", false, "verbose mode")
	flag.Parse()

	if file == "" {
		panic("Data must be specified")
	}

	if mode == "learn" {
		flag.Parse()
		X, y := LoadFromFile(file)
		p := NewAdaGrad(lambda, loop)
		p.Fit(X, y)
		SaveModel(p, model)
	} else if mode == "test" {
		p := LoadModel(model)

		X_test, y_test := LoadFromFile(file)
		num_corr := 0.
		n := 0.
		pred_y := []string{}
		for i, X_i := range X_test {
			pred_y_i := p.Predict(X_i)
			pred_y = append(pred_y, pred_y_i)
			if verbose {
				fmt.Println(pred_y_i)
			}
			if pred_y_i == y_test[i] {
				num_corr += 1
			}
			n += 1
		}
		acc := num_corr / n
		confusionMatrix(y_test, pred_y)
		fmt.Println("Acc:", acc)
	} else {
		panic("Invalid mode")
	}
}
예제 #19
0
func init() {
	hooks = hook.Hooks{}

	flag.Parse()

	log.SetPrefix("[webhook] ")
	log.SetFlags(log.Ldate | log.Ltime)

	if !*verbose {
		log.SetOutput(ioutil.Discard)
	}

	log.Println("version " + version + " starting")

	// load and parse hooks
	log.Printf("attempting to load hooks from %s\n", *hooksFilePath)

	err := hooks.LoadFromFile(*hooksFilePath)

	if err != nil {
		if !*verbose && !*noPanic {
			log.SetOutput(os.Stdout)
			log.Fatalf("couldn't load any hooks from file! %+v\naborting webhook execution since the -verbose flag is set to false.\nIf, for some reason, you want webhook to start without the hooks, either use -verbose flag, or -nopanic", err)
		}

		log.Printf("couldn't load hooks from file! %+v\n", err)
	} else {
		log.Printf("loaded %d hook(s) from file\n", len(hooks))

		for _, hook := range hooks {
			log.Printf("\t> %s\n", hook.ID)
		}
	}
}
예제 #20
0
파일: main.go 프로젝트: cursesun/fabio
func main() {
	var filename string
	var v bool
	flag.StringVar(&filename, "cfg", "", "path to config file")
	flag.BoolVar(&v, "v", false, "show version")
	flag.Parse()

	if v {
		fmt.Println(version)
		return
	}

	cfg, err := config.Load(filename)
	if err != nil {
		log.Fatalf("[FATAL] %s. %s", version, err)
	}

	log.Printf("[INFO] Runtime config\n" + toJSON(cfg))
	log.Printf("[INFO] Version %s starting", version)
	log.Printf("[INFO] Go runtime is %s", runtime.Version())

	initRuntime(cfg)
	initMetrics(cfg)
	initBackend(cfg)
	go watchBackend()
	startAdmin(cfg)
	startListeners(cfg.Listen, cfg.Proxy.ShutdownWait, newProxy(cfg))
	registry.Default.Deregister()
}
예제 #21
0
파일: main.go 프로젝트: rdallman/t
func main() {
	flag.Parse()
	narg := flag.NArg()
	args := flag.Args()
	if narg < 1 {
		usage()
		os.Exit(1)
	}

	pat := args[0]

	// get file infos to make sure we only have real files
	files, errc := gatherFiles(args[1:])
	go func() {
		err := <-errc
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}()

	pres := preBmBc(pat)
	for f := range files {
		// TODO concurrent pipeline
		txt, err := ioutil.ReadFile(f)
		if err != nil {
			continue // TODO err chan ?
		}
		// TODO concurrent pipeline
		found := search(pat, string(txt), pres)
		pnt(f, string(txt), found, 0)
	}
}
예제 #22
0
파일: main.go 프로젝트: schulze/trials
func main() {
	flag.Parse()

	table := make(map[uint64]*big.Int)
	keys := make(chan *rsa.PrivateKey)

	go func() {
		d := time.Tick(time.Minute)
		for {
			<-d
			log.Printf("checked %v keypairs\n", len(table))
		}
	}()

	runtime.GOMAXPROCS(runtime.NumCPU())
	for i := 0; i < runtime.NumCPU(); i++ {
		go generate(keys)
	}

	for {
		priv := <-keys
		check(table, priv.Primes[0])
		check(table, priv.Primes[1])
	}
}
예제 #23
0
파일: main.go 프로젝트: npe9/minimega
func main() {
	flag.Usage = usage
	flag.Parse()

	if *f_version {
		fmt.Println("miniccc", version.Revision, version.Date)
		fmt.Println(version.Copyright)
		os.Exit(0)
	}

	logSetup()

	// signal handling
	sig := make(chan os.Signal, 1024)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM)

	// start a ron client
	var err error
	c, err = ron.NewClient(*f_port, *f_parent, *f_serial, *f_path)
	if err != nil {
		log.Fatal("creating ron node: %v", err)
	}

	log.Debug("starting ron client with UUID: %v", c.UUID)

	go client()

	<-sig
	// terminate
}
예제 #24
0
func main() {
	flag.Usage = usage
	flag.Parse()

	if flag.NArg() == 0 {
		// Read from stdin
		if err := display(os.Stdin); err != nil {
			log.Fatal(err)
		}
	} else {
		for _, filename := range flag.Args() {
			// Skip errors and directories
			if fi, err := os.Stat(filename); err != nil || fi.IsDir() {
				continue
			}

			f, err := os.Open(filename)
			if err != nil {
				log.Fatal(err)
			}
			defer f.Close()

			if err := display(f); err != nil {
				log.Fatal(err)
			}
		}
	}
}
예제 #25
0
func main() {

	// Load command line options.
	flag.Parse()

	// Load the YAML config.
	config, _ = kingologs.CreateConfig(*configFile)

	// Set up the logger based on the configuration.
	var logger kingologs.Logger
	if config.Debug.Verbose {
		logger = *kingologs.CreateLogger(os.Stdout, os.Stdout, os.Stdout, os.Stderr)
		logger.Info.Println("Debugging mode enabled")
		logger.Info.Printf("Loaded Config: %v", config)
	} else {
		logger = *kingologs.CreateLogger(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)
	}

	// Start our syslog 'server'
	srv := kingologs.NewServer(logger, config)

	// Create the Kinesis relay.
	kr := kingologs.NewKinesisRelay(logger, config)

	// Tell the server to send new messages to the Kinesis relay channel
	srv.SetTargetChan(kr.Pipe)
	srv.StartServer()

	// Start the actual relaying to Kinesis
	go kr.StartRelay()

	logger.Trace.Println("Done setting up")
	select {} // block forever
}
예제 #26
0
func main() {
	var (
		config Config
	)

	configFileName := flag.String("config", "", "Config file")
	headerReport := flag.Bool("headerReport", false, "Produce a report of header mappings")
	flag.Parse()

	configFile, err := os.Open(*configFileName)
	if err != nil {
		fmt.Println("Error opening config:", err)
		return
	}
	defer configFile.Close()
	configBuf := new(bytes.Buffer)
	configBuf.ReadFrom(configFile)
	xml.Unmarshal(configBuf.Bytes(), &config)

	// Parse templates
	textTemplates, err := makeTemplates(&config.TemplateConfig)
	if err != nil {
		panic(err)
	}

	// Process each input file config
	for _, fileConfig := range config.FileConfig {
		if *headerReport {
			processHeader(fileConfig, textTemplates)
			continue
		}
		processFile(fileConfig, textTemplates)
	}
}
예제 #27
0
파일: main.go 프로젝트: shawnps/budget
func main() {
	flag.Parse()
	b, err := parseFile(fmt.Sprintf("%s/%s.txt", *dir, *month))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Total:", b.Total)
	fmt.Println("Remaining:", b.Remaining)
	mon := *month
	year, err := strconv.Atoi(mon[0:4])
	if err != nil {
		log.Fatal(err)
	}
	m, err := strconv.Atoi(mon[4:6])
	if err != nil {
		log.Fatal(err)
	}
	rpd := b.Remaining / float64(daysIn(time.Month(m), year)-time.Now().Day())
	fmt.Printf("Remaining/day: %.2f\n", rpd)
	top := map[string]float64{}
	for _, t := range b.Transactions {
		top[t.Name] += t.Cost
	}
	fmt.Println("Top costs:")
	pl := sortMapByValue(top)
	for _, p := range pl {
		fmt.Printf("\t%s: %.2f\n", p.Key, p.Value)
	}
}
예제 #28
0
func main() {
	dbHost := flag.String("dbhost", "localhost", "the database host")
	dbPort := flag.Int("dbport", 5432, "the database port")
	dbUser := flag.String("dbuser", "aclapp", "the database user")
	dbSsl := flag.Bool("dbssl", false, "database ssl config")
	dbName := flag.String("dbname", "acl", "the database name")
	dbPassword := flag.String("dbpass", "", "database password")
	flag.Parse()
	config := pgmapper.DefaultConfig()
	config.Host = *dbHost
	config.Port = *dbPort
	config.User = *dbUser
	config.Ssl = *dbSsl
	config.Database = *dbName
	config.Password = *dbPassword
	r := mux.NewRouter()
	mapper, err := pgmapper.New(config)
	if err != nil {
		log.Fatal(err)
	}
	objectIdExtractor := idextractor.MuxIdExtractor("objectId")
	userIdExtractor := idextractor.MuxIdExtractor("userId")
	r.Methods("POST").Path("/objects").Handler(jwtware.New(addObjectHandler(mapper)))
	r.Methods("DELETE").Path("/objects/{objectId}").Handler(jwtware.New(deleteObjectHandler(mapper, objectIdExtractor)))
	r.Methods("GET").Path("/objects/{objectId}/permissions/{userId}").Handler(jwtware.New(getPermissionsHandler(mapper, objectIdExtractor, userIdExtractor)))
	r.Methods("PUT").Path("/objects/{objectId}/permissions").Handler(jwtware.New(upsertPermissionsHandler(mapper, objectIdExtractor)))
	r.Methods("PUT").Path("/sids/{sid}/permissions").Handler(jwtware.New(upsertMultiplePermissionsHandler(mapper, idextractor.MuxIdExtractor("sid"))))
	log.Println("listening on 8080")
	http.ListenAndServe(":8080", r)
}
예제 #29
0
파일: main.go 프로젝트: edvakf/go-libjpeg
func main() {
	flag.Parse()
	file := flag.Arg(0)

	io, err := os.Open(file)
	if err != nil {
		log.Fatalln("Can't open file: ", file)
	}

	img, err := jpeg.Decode(io, &jpeg.DecoderOptions{})
	if img == nil {
		log.Fatalln("Got nil")
	}
	if err != nil {
		log.Fatalln("Got Error: %v", err)
	}

	//
	// write your code here ...
	//

	switch img.(type) {
	case *image.YCbCr:
		log.Println("decoded YCbCr")
	case *image.Gray:
		log.Println("decoded Gray")
	default:
		log.Println("unknown format")
	}
}
예제 #30
0
파일: docker.go 프로젝트: r0b0ticus/docker
func main() {
	if docker.SelfPath() == "/sbin/init" {
		// Running in init mode
		docker.SysInit()
		return
	}
	// FIXME: Switch d and D ? (to be more sshd like)
	flDaemon := flag.Bool("d", false, "Daemon mode")
	flDebug := flag.Bool("D", false, "Debug mode")
	flag.Parse()
	if *flDebug {
		os.Setenv("DEBUG", "1")
	}
	docker.GIT_COMMIT = GIT_COMMIT
	if *flDaemon {
		if flag.NArg() != 0 {
			flag.Usage()
			return
		}
		if err := daemon(); err != nil {
			log.Fatal(err)
		}
	} else {
		if err := runCommand(flag.Args()); err != nil {
			log.Fatal(err)
		}
	}
}