Esempio n. 1
0
File: main.go Progetto: Invacio/rex
func main() {
	flag.Parse()

	if len(os.Args) < 2 {
		log.Fatal("Not enough args")
	}

	body, err := json.EncodeClientRequest("Rexd.Execute", &service.ExecuteArgs{
		Token:  "nyraITVmr61ALZNdf9Ye",
		Name:   "deploy_api",
		Branch: "master",
		Args:   nil,
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, err := http.Post(*apiURL, "application/json", bytes.NewReader(body))
	if err != nil {
		log.Fatal(err)
	}

	rb, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	log.Print(string(rb))
}
Esempio n. 2
0
func main() {
	flag.Parse()

	var err error
	session, err := r.Connect(r.ConnectOpts{
		Hosts:    strings.Split(*rethinkdbName, ","),
		Database: *rethinkdbDatabase,
	})
	if err != nil {
		log.Fatal(err)
	}

	goji.Get("/accounts", listAccounts)
	goji.Post("/accounts", createAccount)
	goji.Get("/accounts/:id", getAccount)
	goji.Put("/accounts/:id", updateAccount)
	goji.Delete("/accounts/:id", deleteAccount)

	goji.Get("/accounts/:id/tokens", listAccountTokens)
	goji.Delete("/accounts/:id/tokens", deleteAccountToken)

	goji.Get("/tokens", listTokens)
	goji.Post("/tokens", createToken)
	goji.Get("/tokens/:id", getToken)
	goji.Put("/tokens/:id", updateToken)
	goji.Delete("/tokens/:id", deleteToken)

	goji.Serve()
}
Esempio n. 3
0
func init() {

	flag.Usage = func() {
		fmt.Printf("Usage: envconv [options] file [files...]\n\n")
		flag.PrintDefaults()
	}

	version := flag.Bool("v", false, "Prints current version")

	flag.Parse()

	if *version {
		fmt.Println("envconf version " + VERSION)
		os.Exit(0)
	}

	templateFuncMap = template.FuncMap{
		"default": func(args ...string) string {
			defer recovery()
			if len(args) <= 0 {
				return ""
			}
			return args[len(args)-1]
		},
		"in": func(arg string, slice []string) bool {
			defer recovery()
			for _, i := range slice {
				if arg == i {
					return true
				}
			}
			return false
		},
	}
}
Esempio n. 4
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	flag.Parse()

	// Connect to RethinkDB
	var err error
	session, err = r.Connect(r.ConnectOpts{
		Address: *rethinkAddress,
	})
	if err != nil {
		log.Fatal(err)
	}

	// Create the database and tables
	r.DbCreate(*rethinkName).Exec(session)
	r.Db(*rethinkName).TableCreate("invites").Exec(session)
	r.Db(*rethinkName).Table("invites").IndexCreate("email").Exec(session)
	r.Db(*rethinkName).Table("invites").IndexCreate("name").Exec(session)

	// Add a CORS middleware
	goji.Use(cors.New(cors.Options{
		AllowCredentials: true,
	}).Handler)

	// Add routes to goji
	goji.Get("/", index)
	goji.Post("/check", check)
	goji.Post("/free", free)
	goji.Post("/create", create)

	// Start the server
	goji.Serve()
}
Esempio n. 5
0
func main() {
	flag.Parse()

	f := finch.NewFinch(*apiToken)

	f.Start()
}
Esempio n. 6
0
File: main.go Progetto: Xe/betterbot
func main() {
	flag.Parse()

	conn, err := common.Connect()
	if err != nil {
		panic(err)
	}
	uplink = conn

	conn.Subscribe(uplink.ID+":input", func(subj, unusedReply string, msg *common.Message) {
		if msg.Kind != "TextMessage" {
			return
		}

		if !strings.HasPrefix(msg.Body, ";source") {
			return
		}

		reply := &common.Message{
			Destination: msg.ReplyTo,
			Kind:        "TextMessage",
			Body:        "Source code: https://github.com/Xe/betterbot",
		}

		conn.Publish(msg.Via+":input", reply)
	})

	conn.Publish("betterbot.birth", &common.Birth{
		ID:         uplink.ID,
		EventKinds: []string{"TextMessage"},
	})

	runtime.Goexit()
}
Esempio n. 7
0
// Serve starts Goji using reasonable defaults.
func Serve() {
	if !flag.Parsed() {
		flag.Parse()
	}

	DefaultMux.Compile()
	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", DefaultMux)

	listener := bind.Default()
	log.Println("Starting Goji on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("Goji received signal, gracefully stopping") })
	graceful.PostHook(func() { log.Printf("Goji stopped") })

	err := graceful.Serve(listener, http.DefaultServeMux)

	if err != nil {
		log.Fatal(err)
	}

	graceful.Wait()
}
Esempio n. 8
0
func main() {
	flag.Parse()

	runtime.GOMAXPROCS(numCPU)

	file, err := os.Open(crontabPath)
	if err != nil {
		log.Fatalf("crontab path:%v err:%v", crontabPath, err)
	}

	parser, err := NewParser(file)
	if err != nil {
		log.Fatalf("Parser read err:%v", err)
	}

	runner, err := parser.Parse()
	if err != nil {
		log.Fatalf("Parser parse err:%v", err)
	}

	file.Close()

	var wg sync.WaitGroup
	shutdown(runner, &wg)

	runner.Start()
	wg.Add(1)

	wg.Wait()
	log.Println("End cron")
}
Esempio n. 9
0
File: main.go Progetto: Invacio/rex
func main() {
	flag.Parse()

	session, err := r.Connect(r.ConnectOpts{
		Address:  *rethinkdbAddress,
		Database: *rethinkdbDatabase,
	})
	if err != nil {
		log.Fatal(err)
	}

	r.DB(*rethinkdbDatabase).TableCreate("scripts").Exec(session)
	r.DB(*rethinkdbDatabase).TableCreate("tokens").Exec(session)

	s := rpc.NewServer()
	s.RegisterCodec(json.NewCodec(), "application/json")
	s.RegisterService(&service.Service{
		Session: session,
	}, "Rexd")
	http.Handle("/rpc", s)

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.Write([]byte("lavab/rexd 0.1.0\n"))
	})

	log.Printf("Binding to %s", *bindAddress)
	if err := http.ListenAndServe(*bindAddress, nil); err != nil {
		log.Fatal(err)
	}
}
Esempio n. 10
0
func main() {
	flag.Parse()
	addr := Host + ":" + Port

	logger.Info("botyardq", "path", DBPath, "host", Host, "port", Port)

	broker = NewBroker(DBPath)
	err := broker.Init()
	if err != nil {
		logger.Error("broker", "err", err)
		os.Exit(1)
	}

	router := httprouter.New()
	router.POST("/v1/queues/:queue", PushHandler)
	router.GET("/v1/queues/:queue", PopHandler)
	router.DELETE("/v1/queues/:queue/:id", DeleteHandler)

	logger.Info("Serving at " + addr)
	err = http.ListenAndServe(addr, router)
	if err != nil {
		log.Error("listen", "err", err)
		os.Exit(1)
	}

	logger.Info("bye")
}
Esempio n. 11
0
func init() {
	rand.Seed(time.Now().Unix())

	rethinkdbHost = flag.String("rethinkdb_host", "localhost", "RethinkDB hostname or IP")
	rethinkdbPort = flag.String("rethinkdb_port", "28015", "Port to connect to RethinkDB")
	env = flag.String("env", "dev", "Application environment - dev/staging/prod")
	tmpTable = flag.String("tmp_table", "tmp_"+uniuri.New(), "Table to save temporary results")
	flag.Parse()
}
Esempio n. 12
0
func main() {
	flag.Parse()

	log = logrus.New()
	if *logFormatterType == "text" {
		log.Formatter = &logrus.TextFormatter{
			ForceColors: *logForceColors,
		}
	} else if *logFormatterType == "json" {
		log.Formatter = &logrus.JSONFormatter{}
	}
	log.Level = logrus.DebugLevel

	if *enableHub || *enableSender {
		var err error
		session, err = r.Connect(r.ConnectOpts{
			Address: *rethinkdbAddress,
		})
		if err != nil {
			log.WithField("error", err.Error()).Fatal("Unable to connect to RethinkDB")
		}

		r.DbCreate(*rethinkdbDatabase).Exec(session)
		r.Db(*rethinkdbDatabase).TableCreate("templates").Exec(session)
		r.Db(*rethinkdbDatabase).Table("templates").IndexCreate("name").Exec(session)
		r.Db(*rethinkdbDatabase).Table("templates").IndexCreate("version").Exec(session)
		r.Db(*rethinkdbDatabase).TableCreate("hub_state").Exec(session)
		r.Db(*rethinkdbDatabase).Table("hub_state").IndexCreate("time").Exec(session)
	}

	up := strings.Split(*usernames, ",")
	pp := strings.Split(*passwords, ",")

	if len(up) != len(pp) {
		log.Fatal("length of usernames and passwords is different")
	}

	if *enableSender {
		go initTemplates()

		for i, username := range up {
			go initSender(username, pp[i])
		}
	}

	if *enableHub {
		change := make(chan struct{})

		go initChurner(change)
		go initHub(change)
	}

	select {}
}
Esempio n. 13
0
func main() {
	flag.Parse()

	router := router.Create(port, env)
	// loggedRouter := handlers.LoggingHandler(os.Stdout, router)

	startApp()
	fmt.Printf("Running on port: %+v \n", port)
	fmt.Printf("Environment: %+v \n", env)
	log.Fatal(http.ListenAndServe(":"+port, router))
}
Esempio n. 14
0
File: main.go Progetto: Xe/betterbot
func main() {
	flag.Parse()

	conn, err := common.Connect()
	if err != nil {
		panic(err)
	}
	uplink = conn

	conn.Subscribe(uplink.ID+":input", func(subj, unusedReply string, msg *common.Message) {
		if msg.Kind != "TextMessage" {
			return
		}

		reply := &common.Message{
			Destination: msg.ReplyTo,
			Kind:        "TextMessage",
		}

		switch msg.Body {
		case ";np":
			body, err := np()
			if err != nil {
				reply.Body = err.Error()
			} else {
				reply.Body = body
			}
		case ";dj":
			body, err := dj()
			if err != nil {
				reply.Body = err.Error()
			} else {
				reply.Body = body
			}
		case ";stats":
			body, err := stats()
			if err != nil {
				reply.Body = err.Error()
			} else {
				reply.Body = body
			}
		}

		conn.Publish(msg.Via+":input", reply)
	})

	conn.Publish("betterbot.birth", &common.Birth{
		ID:         uplink.ID,
		EventKinds: []string{"TextMessage"},
	})

	runtime.Goexit()
}
Esempio n. 15
0
func main() {
	flag.Parse()
	if !actions.validAction(*action) {
		fmt.Println("Please choose a valid action. Available: " + actions.available())
		os.Exit(1)
	}

	err := actions.perform(*action)
	if err != nil {
		fmt.Printf("Error performing %s: %v", *action, err)
	}
}
Esempio n. 16
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU() * 4)

	flag.BoolVar(&printf, "printf", false, "print replies")
	flag.BoolVar(&compress, "compress", false, "compress replies")
	flag.StringVar(&tsig, "tsig", "", "use MD5 hmac tsig: keyname:base64")
	flag.StringVar(&config, "config", "", "alternative configuration file")
	flag.StringVar(&bind_addr, "bind_addr", "127.0.0.1:53", "bind HTTP to HOST and PORT")
	flag.StringVar(&dnsfwd_addr, "dnsfwd_addr", "8.8.8.8:53", "DNS server to forward request to")
	flag.StringVar(&redis_addr, "redis_addr", "127.0.0.1:6379", "address of Redis instance")
	flag.StringVar(&portal_addr, "portal_addr", "127.0.0.1:80", "address of portal")
	flag.StringVar(&log_file, "log_file", "", "path to log file")

	var name, secret string
	flag.Usage = func() {
		flag.PrintDefaults()
	}
	flag.Parse()

	// Setup Log file
	if len(log_file) > 0 {
		f, err := os.OpenFile(log_file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0640)
		defer f.Close()
		if err != nil {
			log.Fatalf("Error opening file: %v", err)
		}
		log.SetOutput(f)
	}

	// Tsig
	if tsig != "" {
		a := strings.SplitN(tsig, ":", 2)
		name, secret = dns.Fqdn(a[0]), a[1] // fqdn the name, which everybody forgets...
	}

	// DNS
	dns.HandleFunc(".", handleAll)

	go serve("tcp", name, secret)
	go serve("udp", name, secret)
	log.Printf("* Running on %s\n", bind_addr)
	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
forever:
	for {
		select {
		case s := <-sig:
			fmt.Printf("Signal (%d) received, stopping\n", s)
			break forever
		}
	}
}
Esempio n. 17
0
func main() {

	proxyUriPtr := flag.String("proxy-url", "", "uri to listen on eg: http://proxy.com")
	originUriPtr := flag.String("origin-url", "", "origin to proxy eg: http://origin.com")
	ssoSecretPtr := flag.String("sso-secret", "", "SSO secret for origin")
	ssoUriPtr := flag.String("sso-url", "", "SSO endpoint eg: http://discourse.forum.com")

	flag.Parse()

	originUrl, err := url.Parse(*originUriPtr)

	if err != nil {
		flag.Usage()
		log.Fatal("invalid origin url")
	}

	_, err = url.Parse(*ssoUriPtr)

	if err != nil {
		flag.Usage()
		log.Fatal("invalid sso url, should point at Discourse site with enable sso")
	}

	proxyUrl, err2 := url.Parse(*proxyUriPtr)

	if err2 != nil {
		flag.Usage()
		log.Fatal("invalid proxy uri")
	}

	if *proxyUriPtr == "" || *originUriPtr == "" || *ssoSecretPtr == "" || *ssoUriPtr == "" {
		flag.Usage()
		os.Exit(1)
		return
	}

	cookieSecret := uuid.New()

	proxy := httputil.NewSingleHostReverseProxy(originUrl)

	handler := redirectIfCookieMissing(proxy, *ssoSecretPtr, cookieSecret, *ssoUriPtr)

	server := &http.Server{
		Addr:           proxyUrl.Host,
		Handler:        handler,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	log.Fatal(server.ListenAndServe())
}
Esempio n. 18
0
File: 3do.go Progetto: 3onyc/3do
func main() {
	flag.Parse()

	router := mux.NewRouter()
	db := initDB()

	ctx := util.NewContext(router, db)
	initRoutes(ctx)
	seedDB(ctx)

	addStaticRoute(router)
	startHTTPServer(router)
}
func init() {
	flag.IntVar(&WebPort, "web-port", 8080, "Port to bind to")
	flag.StringVar(&EndPointURL, "endpoint", "http://*****:*****@getfishtank.ca", "SMTP username")
	flag.StringVar(&SmtpPassword, "smtp-password", "", "SMTP password")

	flag.StringVar(&DatabaseStore, "database", "mongodb://127.0.0.1:27017/model", "database")

	flag.StringVar(&GplusKey, "gplus-key", "1049113770955-agedcvcoi68qlbc9mm321odb5qdqlgrg.apps.googleusercontent.com", "Google+ OAuth Key")
	flag.StringVar(&GplusSecret, "gplus-secret", "TjdRDltddkFtlx9dyStuaa5w", "Google+ OAuth Secret")
	flag.StringVar(&FacebookKey, "facebook-key", "1667094910175363", "facebook key")
	flag.StringVar(&FacebookSecret, "facebook-secret", "63472dc2deb3269d298f529cc727b9f2", "facebook secret")
	flag.StringVar(&TwitterKey, "twitter-key", "QVO8QAPqpvnfX6CY3291GkauQ", "twitter key")
	flag.StringVar(&TwitterSecret, "twitter-secret", "YpaY8TsSR2aLOJh4o9XIqXSgtRubhACmRI2oWTPJs608hdJYv9", "twitter secret")

	flag.Parse()
	log.Printf("Config file						%s", config)
	log.Printf("Web folder						%s", StaticAssets)
	log.Printf("Web host						%s", WebHost)
	log.Printf("Web port						%s", WebPort)
	log.Printf("End point						%s", EndPointURL)
	log.Printf("Use SSL							%s", UseSSL)
	log.Printf("certification file				%s", CertFile)
	log.Printf("key file						%s", KeyFile)
	log.Printf("run folder						%s", RunFolder)
	log.Printf("template folder					%s", TemplateFolder)
	log.Printf("end point						%s", EndPointURL)
	log.Printf("SMTP host						%s", SmtpHost)
	log.Printf("SMTP port 						%s", SmtpPort)
	log.Printf("SMTP username					%s", SmtpUsername)
	log.Printf("SMTP password					%s", SmtpPassword)
	log.Printf("Database						%s", DatabaseStore)
	log.Printf("JWT File						%s", JwtFile)
	log.Printf("Google plus						%s", GplusKey)
	log.Printf("Google Secret					%s", GplusSecret)
	log.Printf("facebook						%s", FacebookKey)
	log.Printf("facebook secret					%s", FacebookSecret)
	log.Printf("twitter							%s", TwitterKey)
	log.Printf("twitter secret					%s", TwitterSecret)

}
Esempio n. 20
0
File: main.go Progetto: Xe/betterbot
func main() {
	flag.Parse()

	conn, err := common.Connect()
	if err != nil {
		panic(err)
	}
	uplink = conn

	bot := irc.IRC(*ircNick, *ircUser)
	bot.UseTLS = *ircServerSSL

	bot.AddCallback("*", func(event *irc.Event) {
		msg := eventToMessage(event)

		uplink.Printf("Recieved %q (%s)", msg.Kind, event.Raw)
		uplink.Publish("betterbot.input", msg)
	})

	bot.AddCallback("001", func(e *irc.Event) {
		for _, channel := range strings.Split(*ircChannels, ",") {
			bot.Join(channel)
		}
	})

	conn.Subscribe(uplink.ID+":input", func(subj, reply string, msg *common.Message) {
		kind := ""
		if strings.HasPrefix(msg.Kind, "irc:") {
			kind = strings.TrimPrefix(msg.Kind, "irc:")
		} else {
			for key, value := range verbKind {
				if value == msg.Kind {
					kind = key
					break
				}
			}
		}

		bot.SendRawf("%s %s :%s", kind, msg.Destination, msg.Body)
	})

	err = bot.Connect(*ircServer)
	if err != nil {
		panic(err)
	}

	runtime.Goexit()
}
Esempio n. 21
0
func init() {
	flag.StringVar(&host, "host", "127.0.0.1", "host to bind to")
	flag.IntVar(&port, "port", 2121, "port to bind to")
	flag.StringVar(&username, "ftp-username", "ftp2s3", "FTP username")
	flag.StringVar(&password, "ftp-password", "ftp2s3", "FTP password")
	flag.StringVar(&serverName, "ftp-server-name", "FTP2S3", "FTP server name")

	flag.StringVar(&awsRegion, "aws-region", "us-east-1", "AWS region")
	flag.StringVar(&awsAccessKeyID, "aws-access-key-id", "", "AWS access key ID")
	flag.StringVar(&awsSecretAccessKey, "aws-secret-access-key", "", "AWS secret access key")
	flag.StringVar(&awsBucketName, "aws-bucket-name", "", "S3 bucket name")

	flag.String("config", "", "path to config file")

	flag.Parse()
}
Esempio n. 22
0
File: main.go Progetto: Xe/betterbot
func main() {
	flag.Parse()

	pool = newPool(*redisServer)

	conn, err := common.Connect()
	if err != nil {
		panic(err)
	}
	uplink = conn

	conn.QueueSubscribe("betterbot.birth", "router", subBirth)
	conn.QueueSubscribe("betterbot.input", "router", subInput)

	runtime.Goexit()
}
Esempio n. 23
0
func NewSettings(version, home string, locations []string) (*Settings, error) {
	location := searchConfig(locations)
	if location == "" {
		msg := "Unable to find mediagui.conf\nIt should be placed at any these locations:\n$HOME/.mediagui/\n/usr/local/etc\n<app directory>"
		return nil, errors.New(msg)
	}

	var config, dataDir, webDir, logDir, mediaFolders, ginMode, cpuprofile, unraidHosts string
	var logtostderr, unraidMode bool
	flag.BoolVar(&logtostderr, "logtostderr", true, "true/false log to stderr")
	flag.StringVar(&config, "config", "", "config location")
	flag.StringVar(&dataDir, "datadir", filepath.Join(home, ".mediagui/db"), "folder containing the database files")
	flag.StringVar(&webDir, "webdir", filepath.Join(home, ".mediagui/web"), "folder where web app will be read from")
	flag.StringVar(&logDir, "logdir", "", "folder where log file will be written to")
	flag.StringVar(&mediaFolders, "mediafolders", "/mnt/user/films", "folders that will be scanned for media")
	flag.StringVar(&ginMode, "gin_mode", "release", "gin mode")
	flag.StringVar(&cpuprofile, "cpuprofile", "", "write cpu profile to file")
	flag.BoolVar(&unraidMode, "unraid_mode", true, "if true the app will work distributed with a service running on the unraid host")
	flag.StringVar(&unraidHosts, unraidHosts, "wopr|hal", "specify which unraid hosts will be scanned for movies. the service agent must be running in that host")

	flag.Set("config", location)
	flag.Parse()

	// fmt.Printf("mediaFolders: %s\n", mediaFolders)

	s := &Settings{}
	if mediaFolders == "" {
		s.MediaFolders = make([]string, 0)
	} else {
		s.MediaFolders = strings.Split(mediaFolders, "|")
	}
	s.Version = version
	s.DataDir = dataDir
	s.WebDir = webDir
	s.LogDir = logDir
	s.Location = location
	s.GinMode = ginMode
	s.CpuProfile = cpuprofile
	s.UnraidMode = unraidMode
	if unraidHosts == "" {
		s.UnraidHosts = make([]string, 0)
	} else {
		s.UnraidHosts = strings.Split(unraidHosts, "|")
	}

	return s, nil
}
Esempio n. 24
0
File: main.go Progetto: Xe/betterbot
func main() {
	flag.Parse()

	conn, err := common.Connect()
	if err != nil {
		panic(err)
	}
	uplink = conn

	conn.Subscribe(uplink.ID+":input", func(subj, unusedReply string, msg *common.Message) {
		if msg.Kind != "TextMessage" {
			return
		}

		if strings.HasPrefix(msg.Body, ";") {
			return
		}

		reply := &common.Message{
			Destination: msg.ReplyTo,
			Kind:        "TextMessage",
		}

		var replyMsg string
		var err error
		if strings.Contains(msg.Body, "animate me") {
			replyMsg, err = giphySearch(helperExtractTerms("animate me", msg.Body))
		} else if strings.Contains(msg.Body, "image me") {
			replyMsg, err = imageMe(helperExtractTerms("image me", msg.Body), msg.Sender)
		}

		if err != nil {
			reply.Body = err.Error()
		} else {
			reply.Body = replyMsg
		}

		conn.Publish(msg.Via+":input", reply)
	})

	conn.Publish("betterbot.birth", &common.Birth{
		ID:         uplink.ID,
		EventKinds: []string{"TextMessage"},
	})

	runtime.Goexit()
}
Esempio n. 25
0
func main() {
	var (
		rootDir   string
		assetPath string
		srvPath   string
		ui        string
	)

	flag.StringVar(&rootDir, "root-dir", "/home/vagrant/go/src/github.com/bentrevor/calhoun", "project root")
	flag.StringVar(&assetPath, "asset-path", "web/assets", "asset path")
	flag.StringVar(&srvPath, "srv-path", fmt.Sprintf("%s/images/srv", assetPath), "path to save uploaded files")
	flag.StringVar(&ui, "ui", "web", "")

	flag.Parse()

	var server app.CalhounServer
	postgresDB := db.NewPostgresDB("dev")
	realFS := db.RealFS{RootDir: srvPath}
	store := app.CalhounStore{DB: postgresDB, FS: realFS, SrvPath: srvPath}
	calhoun := app.Calhoun{Store: store}

	switch ui {
	case "web":
		calhoun.Renderer = web.BrowserRenderer{
			ViewsPath:  fmt.Sprintf("%s/web/views", rootDir),
			PhotosPath: srvPath,
		}

		server = &web.WebServer{
			App:           calhoun,
			AssetPath:     assetPath,
			FullAssetPath: fmt.Sprintf("%s/%s", rootDir, assetPath),
		}
	case "cli":
		calhoun.Renderer = cli.ConsoleRenderer{}

		server = cli.ConsoleServer{
			App:  calhoun,
			Args: flag.Args(),
		}
	default:
		log.Fatal(ui, " not supported")
	}

	app.Run("dev", server)
}
Esempio n. 26
0
func main() {
	// Parse the flags
	flag.Parse()

	// Ensure that admin token and commit are set
	if *token == "" || *commit == "" {
		log.Fatal("Invalid arguments")
	}

	// Try to load all files
	files := map[string]string{}
	for _, path := range flag.Args() {
		data, err := ioutil.ReadFile(path)
		if err != nil {
			log.Fatal(err)
		}

		files[path] = string(data)
	}

	// JSON-encode the files
	input, err := json.Marshal(&files)
	if err != nil {
		log.Fatal(err)
	}

	// Send it to the API
	req, err := http.NewRequest("POST", *apiURL+"/maps/"+*commit, bytes.NewReader(input))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	req.Header.Set("Authorization", "Bearer "+*token)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}

	// Write the result
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("%d: %s", resp.StatusCode, string(body))
}
Esempio n. 27
0
func main() {
	flag.Parse()
	fmt.Println("Weather-service params, for more info use -help option:")
	fmt.Println("\t-Port: " + port)
	fmt.Println("\t-openweather app id: " + openWeatherAppId)

	fmt.Println("Bootstrapping system...")
	forecastInteractor := new(usecases.ForecastInteractor)
	forecastInteractor.ForecastRepository = interfaces.NewRestForecastRepo(&http.Client{}, openWeatherAppId)

	webserviceHandler := interfaces.WebserviceHandler{}
	webserviceHandler.ForecastInteractor = forecastInteractor

	mux := routes.New()
	mux.Get("/forecast", webserviceHandler.GetForecast)
	http.Handle("/", mux)
	fmt.Println("Bootstrapping web service...")
	log.Fatal(http.ListenAndServe(":"+port, nil))
}
Esempio n. 28
0
func main() {
	flag.Parse()

	s := syslog.NewServer()
	s.AddHandler(newHandler())
	err := s.Listen(*bind)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Listening to %s", *bind)

	sc := make(chan os.Signal, 2)
	signal.Notify(sc, syscall.SIGTERM, syscall.SIGINT)
	<-sc

	log.Print("Shutdown the server...")
	s.Shutdown()
	log.Print("Server is down")
}
Esempio n. 29
0
File: main.go Progetto: Xe/betterbot
func main() {
	flag.Parse()

	conn, err := common.Connect()
	if err != nil {
		panic(err)
	}
	uplink = conn

	conn.Subscribe(uplink.ID+":input", func(subj, unusedReply string, msg *common.Message) {
		if msg.Kind != "TextMessage" {
			return
		}

		if !strings.HasPrefix(msg.Body, ";printerfact") {
			return
		}

		reply := &common.Message{
			Destination: msg.ReplyTo,
			Kind:        "TextMessage",
		}

		fact, err := getPrinterFact()
		if err != nil {
			reply.Body = err.Error()
			return
		} else {
			reply.Body = fact
		}

		conn.Publish(msg.Via+":input", reply)
	})

	conn.Publish("betterbot.birth", &common.Birth{
		ID:         uplink.ID,
		EventKinds: []string{"TextMessage"},
	})

	runtime.Goexit()
}
Esempio n. 30
0
func main() {
	var (
		config string
		length float64
		age    int
		name   string
		female bool
	)

	flag.StringVar(&config, "config", "", "help message")
	flag.StringVar(&name, "name", "", "help message")
	flag.IntVar(&age, "age", 0, "help message")
	flag.Float64Var(&length, "length", 0, "help message")
	flag.BoolVar(&female, "female", false, "help message")

	flag.Parse()

	fmt.Println("length:", length)
	fmt.Println("age:", age)
	fmt.Println("name:", name)
	fmt.Println("female:", female)
}