예제 #1
1
파일: main.go 프로젝트: xiaobodu/gotunnel
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
1
func main() {
	help := flag.Bool("help", false, "Show usage")
	username := flag.String("u", "", "Specify Github user")
	password := flag.String("p", "", "Specify Github password")

	flag.Usage = func() {
		fmt.Printf("Usage:\n")
		flag.PrintDefaults()
	}
	flag.Parse()

	if *help == true || *username == "" || *password == "" {
		flag.Usage()
		return
	}

	ghc, err := ghclient.NewGithubClient(*username, *password, ghclient.AUTH_USER_PASSWORD)

	gistsc := ghgists.NewGists(ghc)

	res, err := gistsc.GetPublicGistsList()

	jr, err := res.Json()

	fmt.Printf("JSON: %v\nERROR: %v\n", jr, err)

	print("\n\nLOADING NEXT PAGE...\n\n")
	res, err = res.GetNextPage()

	jr, err = res.Json()

	fmt.Printf("JSON: %v\nERROR: %v\n", jr, err)
}
예제 #3
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)

}
func init() {
	condition = flag.String("condition", "<ID>", "Condition ID, set only to check a single alert (optional)")
	stream = flag.String("stream", "<ID>", "Stream ID (mandatory)")
	api_url = flag.String("url", "http://localhost:12900", "URL to Graylog2 api (optional)")
	user = flag.String("user", "<username>", "API username (mandatory)")
	pass = flag.String("password", "<password>", "API password (mandatory)")
}
예제 #5
1
func main() {
	introText := "SIMPLE TWITTER REFORMATTER \n (╯°□°)╯︵ ┻━┻) \n"
	fmt.Printf(introText)

	key := flag.String("key", "nokey", "Twitter consumer key")
	secret := flag.String("sec", "nosecret", "Twitter consumer secret")
	debug := flag.Bool("debug", false, "Debug logging level")
	numTweets := flag.Int("num", 3, "Number of tweets to retrieve")

	flag.Parse()

	access_token, err := getBearerToken(*key, *secret, *debug)
	if err != nil || access_token == "" {
		log.Fatal("Could not retrieve token to make twitter API request")
		os.Exit(1)
	}

	// Create a very basic channel with tweets getting passed into the expander
	// Wait for it to finish executing before quiting.
	var tweetChannel chan string = make(chan string)
	var wg sync.WaitGroup
	wg.Add(1)
	go tweetRetriever(access_token, *numTweets, tweetChannel, &wg, *debug)
	go textExpander(tweetChannel)
	wg.Wait()
}
예제 #6
0
파일: main.go 프로젝트: pyos/webmcast
func main() {
	rand.Seed(time.Now().UTC().UnixNano())
	bind := flag.String("bind", ":8000", "The network ([ip]:port) to bind on.")
	addr := flag.String("addr", "", "The public address (host[:port]) of this node.")
	ephemeral := flag.Bool("ephemeral", false, "Use a process-local in-memory userless database. Can only be enabled in joint mode.")
	flag.Parse()

	if *ephemeral && *addr != "" {
		log.Fatal("-ephemeral cannot be used with -addr. Running as a part of a cluster requires coordination through a database.")
	}

	ctx := Context{
		Database:        NewAnonDatabase(),
		SecureKey:       []byte("12345678901234567890123456789012"),
		StreamKeepAlive: 10 * time.Second,
	}
	if !*ephemeral {
		var err error
		if ctx.Database, err = NewSQLDatabase(*addr, "sqlite3", "development.db"); err != nil {
			log.Fatal("Could not connect to database: ", err)
		}
	}

	mux := http.NewServeMux()
	mux.Handle("/static/", http.FileServer(disallowDirectoryListing(".")))
	mux.Handle("/stream/", UnsafeHandler{NewRetransmissionHandler(&ctx)})
	mux.Handle("/", UnsafeHandler{NewUIHandler(&ctx)})
	log.Fatal(http.ListenAndServe(*bind, mux))
}
예제 #7
0
func main() {
	var statsdHost = flag.String("statsd_host", "127.0.0.1", "Statsd host")
	var statsdPort = flag.Int("statsd_port", 8125, "Statsd host")
	var nodename = flag.String("nodename", "riak", "Riak node name")
	var riakHost = flag.String("riak_host", "127.0.0.1", "Riak host")
	var riakHttpPort = flag.Int("riak_http_port", 8098, "Riak HTTP port")
	flag.Parse()

	// First ping to node to make sure it works
	err := pingRiak(*riakHost, *riakHttpPort)
	if err != nil {
		log.Fatalf("Error: %v", err)
		os.Exit(1)
	}
	statsd := fmt.Sprintf("%s:%d", *statsdHost, *statsdPort)
	addr, err := net.ResolveUDPAddr("udp", statsd)
	if err != nil {
		log.Fatalf("Couldn't resolve UDP addr: %v", err)
		os.Exit(1)
	}
	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		log.Fatalf("Couldn't connect to statsd at %s", statsd)
		os.Exit(1)
	}

	// every 60s run hit the stats endpoint and then send to statsd
	interval := time.NewTicker(time.Second * 60)
	for _ = range interval.C {
		go getAndSendRiakMetrics(conn, *nodename, *riakHost, *riakHttpPort)
	}
}
예제 #8
0
func main() {
	var (
		listenAddress = flag.String("web.listen-address", ":9107", "Address to listen on for web interface and telemetry.")
		metricsPath   = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
		consulServer  = flag.String("consul.server", "localhost:8500", "HTTP API address of a Consul server or agent.")
		kvPrefix      = flag.String("kv.prefix", "", "Prefix from which to expose key/value pairs.")
		kvFilter      = flag.String("kv.filter", ".*", "Regex that determines which keys to expose.")
	)
	flag.Parse()

	exporter := NewExporter(*consulServer, *kvPrefix, *kvFilter)
	prometheus.MustRegister(exporter)

	log.Infof("Starting Server: %s", *listenAddress)
	http.Handle(*metricsPath, prometheus.Handler())
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
             <head><title>Consul Exporter</title></head>
             <body>
             <h1>Consul Exporter</h1>
             <p><a href='` + *metricsPath + `'>Metrics</a></p>
             </body>
             </html>`))
	})
	log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
예제 #9
0
파일: docker.go 프로젝트: neomantra/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")
	bridgeName := flag.String("b", "", "Attach containers to a pre-existing network bridge")
	pidfile := flag.String("p", "/var/run/docker.pid", "File containing process PID")
	flag.Parse()
	if *bridgeName != "" {
		docker.NetworkBridgeIface = *bridgeName
	} else {
		docker.NetworkBridgeIface = docker.DefaultNetworkBridge
	}
	if *flDebug {
		os.Setenv("DEBUG", "1")
	}
	docker.GIT_COMMIT = GIT_COMMIT
	if *flDaemon {
		if flag.NArg() != 0 {
			flag.Usage()
			return
		}
		if err := daemon(*pidfile); err != nil {
			log.Fatal(err)
		}
	} else {
		if err := runCommand(flag.Args()); err != nil {
			log.Fatal(err)
		}
	}
}
예제 #10
0
func main() {
	rpcAddr := flag.String("rpcaddr", ":1115", "rpc listen address")
	httpAddr := flag.String("httpaddr", ":8080", "http frontend listen address")
	flag.Parse()
	var s Server
	f, err := NewHTTPFrontend(*httpAddr)
	if err != nil {
		log.Fatal(err)
	}
	s.HTTPFrontend = f
	rpcplus.Register(&Router{s})
	rpcplus.HandleHTTP()
	go http.ListenAndServe(*rpcAddr, nil)

	d, err := discover.NewClient()
	if err != nil {
		log.Fatal(err)
	}
	if hostPort := strings.SplitN(*rpcAddr, ":", 2); hostPort[0] != "" {
		err = d.RegisterWithHost("flynn-strowger-rpc", hostPort[0], hostPort[1], nil)
	} else {
		err = d.Register("flynn-strowger-rpc", hostPort[1], nil)
	}
	if err != nil {
		log.Fatal(err)
	}

	s.ListenAndServe(nil)
}
예제 #11
0
func main() {
	host := flag.String("h", "http://127.0.0.1:8086", "url to influxdb http api")
	dev := flag.Int("v", 100, "amount to modify previous value each step")
	database := flag.String("d", "testdata", "influxdb database")
	prefix := flag.String("p", "sampledata_", "metric prefix")
	metric := flag.String("m", "random-data", "name of metric")
	flag.Parse()

	var tel = telemetry.New(*prefix, (10 * time.Second))
	var reporter = reporters.InfluxReporter{
		Host:     *host,
		Interval: (30 * time.Second),
		Tel:      tel,
		Database: *database,
	}
	reporter.Report()

	var sample = telemetry.NewAverage(tel, *metric, (60 * time.Second))
	var val = 100
	var add = 0
	for {
		add = rand.Intn(*dev) - (*dev / 2)
		if val+add > 0 {
			val = val + add
		}
		sample.Add(tel, float64(val))
		fmt.Printf("added point %v \n", val)
		time.Sleep(3 * time.Second)
	}
}
예제 #12
0
func main() {
	c2bPort := flag.String("-c2b", "7000", "-c2b=portno.Default=7000")
	conf := flag.String("-conf", "config", "-conf=/path/to/conf. Default=./config")
	flag.Parse()

	config := parseConf(*conf)
	fmt.Println("Config:\n", config.ToString())

	var enabledAPIS []api
	for _, v := range config.EnabledAPIS {
		if v == "c2b" {
			enabledAPIS = append(enabledAPIS, c2b.NewAPI(*c2bPort, config))
		}
	}

	fmt.Println("Starting:", config.EnabledAPIS)
	startAPIS(enabledAPIS...)

	serve := make(chan os.Signal)
	signal.Notify(serve, syscall.SIGINT, syscall.SIGTERM) //Submit to user demands to quit, but gracefully yee sir.

	<-serve
	//graceful
	stopAPIS(enabledAPIS...)

}
예제 #13
0
파일: rrda.go 프로젝트: onceking/rrda
func main() {
	header := "-------------------------------------------------------------------------------\n        RRDA (RRDA REST DNS API) 1.01 (c) by Frederic Cambus 2012-2014\n-------------------------------------------------------------------------------"

	host := flag.String("host", "127.0.0.1", "Set the server host")
	port := flag.String("port", "8080", "Set the server port")

	flag.Usage = func() {
		fmt.Println(header)
		fmt.Println("\nUSAGE :")
		flag.PrintDefaults()
	}
	flag.Parse()

	fmt.Println(header)

	fmt.Println("\nListening on :", *host+":"+*port)

	m := pat.New()
	m.Get("/:server/x/:ip", http.HandlerFunc(ptr))
	m.Get("/:server/:domain/:querytype", http.HandlerFunc(query))

	if err := http.ListenAndServe(*host+":"+*port, m); err != nil {
		fmt.Println("\nERROR :", err)
		os.Exit(1)
	}
}
예제 #14
0
파일: gostash.go 프로젝트: hobbs/mustache
func main() {

	data := flag.String("d", "", "Data file")
	template := flag.String("t", "", "Template file")
	flag.Parse()

	if len(*template) == 0 {
		usage()
	}

	var raw []byte
	var err error
	if len(*data) == 0 {
		raw, err = ioutil.ReadAll(os.Stdin)
		if err != nil || len(raw) == 0 {
			usage()
		}
	} else {
		raw, err = ioutil.ReadFile(*data)
		if err != nil || len(raw) == 0 {
			log.Fatal("Could not load file", err)
		}
	}

	var parsed interface{}
	err = json.Unmarshal(raw, &parsed)
	if err != nil {
		log.Fatal("Failed to parse JSON file ", err)
	}

	fmt.Println(mustache.RenderFile(*template, parsed))
}
예제 #15
0
func main() {
	optHost := flag.String("host", "localhost", "Hostname")
	optPort := flag.String("port", "8983", "Port")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	solr := SolrPlugin{
		Protocol: "http",
		Host:     *optHost,
		Port:     *optPort,
		Prefix:   "solr",
	}

	solr.BaseURL = fmt.Sprintf("%s://%s:%s/solr", solr.Protocol, solr.Host, solr.Port)
	solr.loadStats()

	helper := mp.NewMackerelPlugin(solr)

	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = fmt.Sprintf("/tmp/mackerel-plugin-%s-%s-%s", solr.Prefix, *optHost, *optPort)
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}
예제 #16
0
func main() {
	fmt.Printf("hyperion-dashboard%s\n", buildVersion)

	httpAddr := flag.String("http-address", "127.0.0.1:12300", "<addr>:<port> to listen on")
	dsn := flag.String("db", "", "Database source name")
	flag.Parse()

	dataSource := *dsn
	if dataSource == "" {
		if os.Getenv("HYPERION_DB") != "" {
			dataSource = os.Getenv("HYPERION_DB")
		}
	}

	if dataSource == "" {
		flag.Usage()
		log.Fatal("--db or HYPERION_DB not found")
	}

	db, err := NewDBConn(dataSource)
	if err != nil {
		log.Fatal(err.Error())
	}

	router := mux.NewRouter()
	router.HandleFunc("/", db.RecordsHandler)

	recovery := negroni.NewRecovery()
	logger := negroni.NewLogger()

	n := negroni.New(recovery, logger)
	n.UseHandler(router)
	n.Run(*httpAddr)
}
예제 #17
0
func main() {
	host := flag.String("url", "127.0.0.1", "Monitor server")
	appId := flag.String("appId", "", "App id")
	l := flag.String("l", "INFO", "Log level: TRACE, INFO")

	flag.Parse()

	var traceHandle io.Writer
	if *l == "TRACE" {
		traceHandle = os.Stdout
	} else {
		traceHandle = ioutil.Discard
	}
	InitLog(traceHandle, os.Stdout, os.Stdout, os.Stderr)

	Info.Println("Start agent with host =", *host, " and appId =", *appId, " and period 5 sec")

	do := func() {
		cpu, mem, err := getMesosMetrics()
		if err != nil {
			Error.Println("Load metrics error", err)
			return
		}
		Trace.Println("CPU: ", cpu)
		Trace.Println("Memory:", mem)

		sendData(*host, *appId, cpu, cpu, mem)
	}
	schedule(5, do)
	WaitCtrlC()
}
func main() {
	var (
		listenAddress = flag.String("listen-address", ":9120", "Address to listen on for web interface and telemetry.")
		metricsPath   = flag.String("metric-path", "/metrics", "Path under which to expose metrics.")
		apiURL        = flag.String("api-url", "http://localhost:8001/", "Base-URL of PowerDNS authoritative server/recursor API.")
		apiKey        = flag.String("api-key", "", "PowerDNS API Key")
	)
	flag.Parse()

	hostURL, err := url.Parse(*apiURL)
	if err != nil {
		log.Fatalf("Error parsing api-url: %v", err)
	}

	server, err := getServerInfo(hostURL, *apiKey)
	if err != nil {
		log.Fatalf("Could not fetch PowerDNS server info: %v", err)
	}

	exporter := NewExporter(*apiKey, server.DaemonType, hostURL)
	prometheus.MustRegister(exporter)

	log.Infof("Starting Server: %s", *listenAddress)
	http.Handle(*metricsPath, prometheus.Handler())
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
             <head><title>PowerDNS Exporter</title></head>
             <body>
             <h1>PowerDNS Exporter</h1>
             <p><a href='` + *metricsPath + `'>Metrics</a></p>
             </body>
             </html>`))
	})
	log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
예제 #19
0
func main() {
	optHost := flag.String("host", "127.0.0.1", "Hostname")
	optPort := flag.String("port", "6379", "port")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	optDB := flag.String("db", "0", "Database")
	optNamespace := flag.String("namespace", "", "Namespace")
	flag.Parse()

	var sidekiq SidekiqPlugin
	sidekiq.Target = *optHost + ":" + *optPort
	sidekiq.Database = *optDB
	sidekiq.Namespace = *optNamespace
	helper := mp.NewMackerelPlugin(sidekiq)

	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = "/tmp/mackerel-plugin-sidekiq-" + *optHost + "-" + *optPort
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}
예제 #20
0
func main() {

	// You should pass in your client key and secret key as args.
	// Or you can set your access key and secret key by replacing the default values below (2nd input param in flag.String)
	githubClientKey := flag.String("client_key", "[your github client key]", "your oauth client key")
	githubSecretKey := flag.String("secret_key", "[your github secret key]", "your oauth secret key")
	flag.Parse()

	// set the auth parameters
	auth.Config.CookieSecret = []byte("7H9xiimk2QdTdYI7rDddfJeV")
	auth.Config.LoginSuccessRedirect = "/private2"
	auth.Config.CookieSecure = false

	// login handler
	githubHandler := auth.Github(*githubClientKey, *githubSecretKey, "")
	http.Handle("/auth/login", githubHandler)

	// logout handler
	http.HandleFunc("/auth/logout", Logout)

	// public urls
	http.HandleFunc("/", Public)

	// private, secured urls
	http.HandleFunc("/private1", auth.SecureFunc(Private1))
	http.HandleFunc("/private2", auth.SecureUser(Private2))

	println("github demo starting on port 8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println(err)
	}
}
func main() {
	password := flag.String("password", "", "Password for all redis instances")
	db := flag.Int("db", 0, "DB number")
	socket := flag.String("socket", "/tmp/redis-monitor.sock", "Socket to provide metrics over")
	flag.Parse()
	if len(flag.Args()) < 1 {
		flag.Usage()
		os.Exit(1)
	}
	s := &http.Server{
		Handler: &Addresses{
			Addr:     flag.Args(),
			Password: *password,
			DB:       int64(*db),
		},
	}

	l, err := util.CreateSocket(*socket)

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

	defer profile.Start(profile.MemProfile).Stop()

	if err != nil {
		panic(err)
	}

	if err := s.Serve(l); err != nil {
		panic(err)
	}
}
예제 #22
0
func main() {
	var fileName = flag.String("filepath", "", "oss file path")
	var endpoint = flag.String("endpoint", "oss-cn-hangzhou-internal.aliyuncs.com", "oss endpoint")
	flag.Parse()
	if *fileName == "" {
		log.Printf("file name can not be null \n")
		return
	}
	cfg := &oss.Config{Endpoint: *endpoint,
		Key: "", Secret: ""}
	client, _ := oss.NewClient(cfg)
	errFiles, err := CheckGzFile(*fileName, client, "frio-tegong")
	for i := 0; i < 5 && i < len(errFiles); i++ {
		err = client.DeleteObject("frio-tegong", errFiles[i])
		if err != nil {
			log.Printf("delete files failed ! errFiles:%s err:%s\n", errFiles, err)
			return
		}
	}
	if err != nil {
		log.Printf("err:%s \n", err)
		return
	}
	log.Printf("errFiles is %s \n", errFiles)
}
예제 #23
0
func main() {
	srcptr := flag.String("src", "", "source host")
	destptr := flag.String("dest", "", "dest host")
	modePtr := flag.String("mode", "", "r/w/rw")
	flag.Parse()

	if len(*srcptr) == 0 || len(*destptr) == 0 {
		stdlog.Println("must set -src or -dest")
		return
	}
	desthost = *destptr
	mode = *modePtr
	if len(mode) == 0 {
		stdlog.Println("must set -mode [r|w|rw]")
		return
	}

	go runloop()

	r := redis_tool.NewMonitorReader(*srcptr)
	r.DidRecvCommand = recvCommand // bind
	err := r.Connect()
	if err != nil {
		panic(err)
	}
}
예제 #24
0
func main() {
	pwd := os.Getenv("ESENDEX_PASSWORD")

	debug := flag.Bool("debug", false, "don't send SMS")
	user := flag.String("username", "", "esendex username (use ESENDEX_PASSWORD env for password)")
	account := flag.String("account", "", "esendex account")
	listen := flag.String("web.listen-address", "127.0.0.1:2825", "listen address")

	flag.Parse()

	if *user == "" || *account == "" || pwd == "" {
		println("usage\nenv ESENDEX_PASSWORD=<password> gosendex -username <user> -account <account_id>\n-listen.addr\t127.0.0.1:2825\n-debug:\tfalse")
		os.Exit(1)
	}

	ec := ESendexCredentials{
		User:     *user,
		Password: pwd,
		Account:  *account,
	}

	handler := func(w http.ResponseWriter, r *http.Request) *httpError {
		return handle_notify(&ec, w, r, *debug)
	}

	http.Handle("/notify", requestHandler(handler))
	log.Fatal(http.ListenAndServe(*listen, nil))
}
func main() {
	optHost := flag.String("host", "localhost", "Hostname")
	optPort := flag.String("port", "0", "Port")
	optProtocol := flag.String("protocol", "tcp", "tcp or udp")
	optLevel := flag.String("level", "warn", "warn of crit")
	flag.Parse()

	if *optPort == "0" {
		fmt.Println("-port is required")
		os.Exit(UNKNOWN)
	}

	var msg string
	target := fmt.Sprintf("%s:%s", *optHost, *optPort)
	_, err := net.Dial(*optProtocol, target)
	if err != nil {
		switch *optLevel {
		case "crit":
			msg = fmt.Sprintf("CRITICAL: %s://%s closed", *optProtocol, target)
			fmt.Println(msg)
			os.Exit(CRITICAL)
		case "warn":
			msg = fmt.Sprintf("WARNING: %s://%s closed", *optProtocol, target)
			fmt.Println(msg)
			os.Exit(WARNING)
		}
	}
	msg = fmt.Sprintf("OK: %s://%s open", *optProtocol, target)
	fmt.Println(msg)
	os.Exit(OK)
}
예제 #26
0
func main() {
	flag.Usage = usage
	pkgName := flag.String("p", "", "package name, if not speficied using the input file name instead")
	outFile := flag.String("o", "", "output file, if not speficied using stdout instead")
	flag.Parse()
	if len(flag.Args()) < 1 {
		fmt.Fprintf(os.Stderr, "no files to parse provided\n")
		usage()
	}
	// parse files
	src, err := ParseFiles(flag.Args())
	if err != nil {
		log.Fatal(err)
	}
	if *pkgName != "" {
		src.PkgName = *pkgName
	}
	// output file
	var out io.Writer
	if *outFile != "" {
		out, err = os.OpenFile(*outFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		out = os.Stdout
	}
	if err := src.Generate(out); err != nil {
		log.Fatal(err)
	}
}
예제 #27
0
// Parse command line args
func (self *app) parseFlags() error {
	configFile := flag.String("config", "", "Config file")
	showVersion := flag.Bool("version", false, "Show version")
	// Profiling stuff ... from http://blog.golang.org/profiling-go-programs
	cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")

	flag.Parse()

	// -version
	if *showVersion {
		fmt.Printf("Version: %v\n", program_version.GetVersion())
		os.Exit(1)
	}

	// -config "cfg.json"
	if *configFile != "" {
		f, err := os.Open(*configFile)
		if err != nil {
			return fmt.Errorf("Failed to open file '%s': %v", *configFile, err)
		}
		defer f.Close()
		if err := self.parseConfig(f); err != nil {
			return err
		}
	}

	// -cpuprofile "filename.prof"
	if *cpuprofile != "" {
		if err := self.startCpuProfile(*cpuprofile); err != nil {
			return err
		}
	}

	return nil
}
예제 #28
0
func getConfig() Config {
	route := flag.String("route", "small", "The route to call on the server (small|med|large|xlarge)")
	host := flag.String("host", "localhost", "The host of the server")
	port := flag.String("port", "80", "The port of the host server")
	https := flag.Bool("https", false, "Use https as the transfer protocol.")

	apigee := flag.Bool("apigee", false, "Use an apigee request")
	configFile := flag.String("config", "config.json", "Location of config file")

	flag.Parse()

	var config Config

	if *apigee {
		file, err := ioutil.ReadFile(*configFile)
		if err != nil {
			fmt.Printf("File error: %v\n", err)
			os.Exit(1)
		}

		err = json.Unmarshal(file, &config)
		if err != nil {
			fmt.Printf("JSON error: %v\n", err)
			os.Exit(1)
		}
	}

	config.setEndpoint(*route, *host, *port, *https)
	config.UseApigee = *apigee

	return config
}
예제 #29
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)
}
예제 #30
0
func main() {
	optEndpoint := flag.String("endpoint", "", "AWS Endpoint")
	optAccessKeyID := flag.String("access-key-id", "", "AWS Access Key ID")
	optSecretAccessKey := flag.String("secret-access-key", "", "AWS Secret Access Key")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	var ses SESPlugin

	ses.Endpoint = *optEndpoint
	ses.AccessKeyID = *optAccessKeyID
	ses.SecretAccessKey = *optSecretAccessKey

	helper := mp.NewMackerelPlugin(ses)
	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = "/tmp/mackerel-plugin-ses"
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}