示例#1
0
文件: config.go 项目: snikch/api
// init is responsible for initializing the entire configuration environment.
// In development, this means loading in and environment variables from both
// .env.default and .env. The .env.default file is commited into source control
// to provide sane defaults without sharing any secrets, whereas .env is ignored
// and should be used to store local development secrets, such as API keys for
// any services required to run.
func init() {
	_ = godotenv.Load(".env")
	_ = godotenv.Load(".env.default")
	baseDir := os.Getenv("BASE_DIR")
	if baseDir != "" {
		_ = godotenv.Load(baseDir + ".env")
		_ = godotenv.Load(baseDir + ".env.default")
	}

	initSneakerSecrets()
}
示例#2
0
func main() {

	// Load the environment variables we need
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	// Read the port
	port := os.Getenv("PORT")

	tlsConfig, err := getTLSConfig(os.Getenv("SWARM_CREDS_DIR"))
	if err != nil {
		log.Fatal("Could not create TLS certificate.")
	}

	docker, _ := dockerclient.NewDockerClient(os.Getenv("DOCKER_HOST"), tlsConfig)

	mux := mux.NewRouter()
	// mux.HandleFunc("/events", get_events(dbmap)).Methods("GET")
	// mux.HandleFunc("/events/{year}", get_events_by_year(dbmap)).Methods("GET")
	mux.HandleFunc("/spawn", spawn(docker)).Methods("GET")
	mux.HandleFunc("/list-containers", list_containers(docker)).Methods("GET")
	n := negroni.Classic()
	n.UseHandler(mux)
	log.Printf("Listening on port %s\n", port)
	n.Run(":" + port)

}
func run(c *cli.Context) error {
	if c.String("env-file") != "" {
		_ = godotenv.Load(c.String("env-file"))
	}

	plugin := Plugin{
		Repo: Repo{
			Owner: c.String("repo.owner"),
			Name:  c.String("repo.name"),
		},
		Build: Build{
			Event: c.String("build.event"),
		},
		Commit: Commit{
			Ref: c.String("commit.ref"),
		},
		Config: Config{
			APIKey:     c.String("api-key"),
			Files:      c.StringSlice("files"),
			FileExists: c.String("file-exists"),
			Checksum:   c.StringSlice("checksum"),
			Draft:      c.Bool("draft"),
			BaseURL:    c.String("base-url"),
			UploadURL:  c.String("upload-url"),
		},
	}

	return plugin.Exec()
}
示例#4
0
func main() {
	// load up our ENV here. TODO Pass in file names for prod/test
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file. You can't run the app without one!")
	}

	//config.DBHosts = os.Getenv("DATABASE_URL")
	config.DBName = os.Getenv("DATABASE_NAME")
	config.DBUser = os.Getenv("DATABASE_USER")
	//config.DBPassword = os.Getenv("DATABASE_PASSWORD")

	// Starts the app from config package struct. Returns Negroni (the
	// server), Router, Render and Database session
	app := config.StartApp()

	// Make database session available to config package
	//config.Session = app.Session

	// Keep our session open until we're done.
	defer app.DB.Close()

	// Register models here. Calling the Register() function passes our app
	// struct into our model to access the Router and register handlers
	pages.Register(app)
	users.Register(app)

	// start the server on 4567
	port := os.Getenv("PORT")

	// TODO pass in port based on ENV.
	app.Negroni.Run(":" + port)
}
示例#5
0
文件: main.go 项目: unitrans/unitrans
func init() {
	godotenv.Load()
	redisClient = storage.RedisClient(os.Getenv("REDIS_ADDR"), os.Getenv("REDIS_PASS"))
	translator = t.NewTranslateAdapter(
		[]backend_full.IBackendFull{
			backend_full.NewGoogleTranslator(httpclient.GetHttpClient(), os.Getenv("G_TR_KEY")),
			backend_full.NewYandexTranslator(httpclient.GetHttpClient(), os.Getenv("Y_TR_KEY")),
			//			backend_full.NewBingTranslator(os.Getenv("B_TR_KEY")),
		},
		components.NewChain(2),
	)
	//translator.AddParticular(&particular.AbbyyLingvoLiveTranslator{})
	if "" == os.Getenv("APP_SECRET") {
		os.Setenv("APP_SECRET", string(securecookie.GenerateRandomKey(32)))
	}
	cookieStore = &sessions.CookieStore{
		Codecs: securecookie.CodecsFromPairs([]byte(os.Getenv("APP_SECRET"))),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30 * 10,
			//			Secure:true,
			HttpOnly: true,
		},
	}
}
示例#6
0
文件: db.go 项目: naikparag/lego
func GetDBSession() *mgo.Session {

	//	if session == nil {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	if session != nil {
		fmt.Printf("DB: reusing same session")
		return session
	}

	session, err = mgo.Dial("localhost:27017")

	if err != nil {
		log.Fatal("Error Connecting Mongo")
	}

	session.SetMode(mgo.Monotonic, true)

	fmt.Printf("DB: creating new db session")

	return session
}
示例#7
0
func main() {
	logger := log.NewLogfmtLogger(os.Stderr)
	logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC)

	err := godotenv.Load()
	if err != nil {
		logger.Log("level", "fatal", "err", err)
	}

	config := &Config{
		Addr: os.Getenv("ADDR"),
		DSN:  os.Getenv("DSN"),
	}

	db, err := gorm.Open("postgres", config.DSN)
	if err != nil {
		panic(err)
	}

	app := cli.NewApp()

	app.Commands = []cli.Command{{
		Name:   "serve",
		Action: serve(logger, config, db),
	}}

	if err := app.Run(os.Args); err != nil {
		logger.Log("level", "fatal", "err", err)
	}

}
示例#8
0
func InitServer() *martini.ClassicMartini {
	envFileName := martini.Env + ".env"
	err := godotenv.Load(envFileName)
	if err != nil {
		log.Fatalf("Error loading: %s", envFileName)
	}

	m := martini.Classic()
	m.Map(db.Connect())

	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Get("/", func(r render.Render) {
		r.HTML(200, "home", "")
	})
	m.Get("/api/projects", controllers.ProjectIndex)
	m.Get("/api/projects/new", controllers.ProjectNew)
	m.Get("/api/projects/:id", controllers.ProjectGet)
	m.Post("/api/projects", binding.Bind(models.Project{}), controllers.ProjectCreate)
	m.Put("/api/projects/:id", binding.Bind(models.Project{}), controllers.ProjectUpdate)
	m.Delete("/api/projects/:id", controllers.ProjectDelete)

	return m
}
示例#9
0
func main() {
	log.Println("Starting sqs processor")

	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	c.AWSAccess = os.Getenv("AWS_ACCESS")
	c.AWSSecret = os.Getenv("AWS_SECRET")
	done := make(chan bool)
	messageQueue := make(chan *sqs.Message)

	//notification queue
	s, err := sqs.NewFrom(c.AWSAccess, c.AWSSecret, "us-east-1")
	if err != nil {
		log.Panic(err)
	}
	q, err := s.GetQueue("spotify-ofp-notification")
	if err != nil {
		log.Panic(err)
	}

	go listenOnQueue("spotify-ofp", messageQueue)
	go processQueue(messageQueue)
	go polling(q)
	<-done
}
示例#10
0
func LoadEnvironment(env string) (err error) {
	if !isValidEnvironment(env) {
		return fmt.Errorf("'%s' is not one of the supported enviroments: %v", env, strings.Join(Environments, ","))
	}
	Env = env

	// Load environment variables
	envFileName := Env + ".env"
	if err = godotenv.Load(envFileName); err != nil {
		return
	}

	// Connect to database
	if err = connectDB(); err != nil {
		return
	}

	// Initialize render
	Render = render.New(render.Options{
		Directory:     "templates",
		Layout:        "",
		Delims:        render.Delims{Left: "{{%", Right: "%}}"},
		Extensions:    []string{".tmpl", ".html"},
		IsDevelopment: Env == EnvDevelopment,
	})

	return
}
示例#11
0
func run(c *cli.Context) error {
	if c.String("env-file") != "" {
		_ = godotenv.Load(c.String("env-file"))
	}

	plugin := Plugin{
		Repo: Repo{
			Owner: c.String("repo.owner"),
			Name:  c.String("repo.name"),
		},
		Commit: Commit{
			Sha:    c.String("commit.sha"),
			Ref:    c.String("commit.ref"),
			Branch: c.String("commit.branch"),
			Author: c.String("commit.author"),
			Link:   c.String("commit.link"),
		},
		Build: Build{
			Number: c.Int("build.number"),
			Event:  c.String("build.event"),
			Status: c.String("build.status"),
			Deploy: c.String("build.deploy"),
			Link:   c.String("build.link"),
		},
		Config: Config{
			Webhook: c.StringSlice("webhook"),
		},
	}

	return plugin.Exec()
}
func main() {
	if martini.Env != "production" {
		err := godotenv.Load()
		if err != nil {
			log.Fatal(err)
		}
	}

	mondoApiUri := os.Getenv("MONDO_API_URI")
	mondoAccessToken := os.Getenv("MONDO_ACCESS_TOKEN")
	addr := os.Getenv("ATTACHMENT_PUBLISHER_ADDR")
	vendors := os.Getenv("ATTACHMENT_PUBLISHER_VENDORS")
	if vendors == "" {
		log.Fatalf("no vendors configured!")
	}
	controllers.Vendors = strings.Split(vendors, ",")

	m := martini.Classic()
	mondoApiClient := &mondo.MondoApiClient{Url: mondoApiUri, AccessToken: mondoAccessToken}
	m.Map(matcher)
	m.Map(mondoApiClient)
	m.Post("/webhooks/mondo/transaction", controllers.PostMondoWebhook)
	m.Post("/webhooks/email", controllers.PostEmailWebhook)
	m.Get("/", func() string {
		return "Hello Mondo crowd!"
	})

	m.RunOnAddr(addr)
}
示例#13
0
文件: db.go 项目: zannet/lego
func GetDBSession() *mgo.Session {

	//	if session == nil {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	if session != nil {
		fmt.Printf("DB: reusing same session")
		return Session
	}

	session, err = mgo.Dial(os.Getenv("MONGO_URL"))

	if err != nil {
		panic(err)
	}

	session.SetMode(mgo.Monotonic, true)

	fmt.Printf("DB: creating new db session")

	return session.Clone()
}
示例#14
0
func init() {
	godotenv.Load("../.env")
	stathat = &Stathat{
		StatName: os.Getenv("STATHAT_STAT_NAME"),
		Ezkey:    os.Getenv("STATHAT_EZKEY"),
	}
}
示例#15
0
func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatalln("Error loading .env file")
		os.Exit(-1)
	}

	if len(os.Args) < 2 {
		log.Fatalln(usage())
		os.Exit(-1)
	}

	os.Getenv("NEIGHBORS")

	m := mux.Mux{
		Handlers: Handlers,
	}

	Port := os.Args[1]

	s := server.New(
		Type,
		Host,
		Port,
		m,
		Protocol,
		Logger,
	)

	s.Serve()
}
示例#16
0
func main() {
	if godotenv.Load() != nil {
		log.Fatal("Can't load .env file")
	}

	client, err := docker.NewClientFromEnv()
	if err != nil {
		log.Fatal("Err: %v", err)
	}

	dockerHost := os.Getenv("COURIER_DOCKER_HOST")
	if dockerHost == "" {
		dockerHost = "localhost"
	}

	proxy := &Proxy{
		Transport:    http.DefaultTransport,
		DockerHost:   dockerHost,
		DockerClient: client,
	}

	port := os.Getenv("COURIER_PORT")
	if port == "" {
		port = "8080"
	}

	log.Printf("Listen %s", port)
	runtime.GOMAXPROCS(runtime.NumCPU())
	http.ListenAndServe(":"+port, proxy)
}
示例#17
0
func main() {
	watchDir, targetDir := "tmp/source", "tmp/target"

	godotenv.Load(".env")

	fm, err := fm.NewFM("mms_prod")
	if err != nil {
		panic(err)
	}
	defer fm.Destroy()

	fm.Watch(watchDir, targetDir)

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)
	go func() {
		<-c
		fmt.Println("Bye Bye")
		fm.Destroy()
		os.Exit(0)
	}()

	quit := make(chan bool, 1)
	/*
		for {
			fmt.Println("sleeping...")
			time.Sleep(10 * time.Second) // or runtime.Gosched() or similar per @misterbee
		}
	*/
	<-quit
}
示例#18
0
func init() {
	// Load environment variables from .env file.
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
}
示例#19
0
func main() {
	flag.Parse()

	err := godotenv.Load(fmt.Sprintf("config/%s.env", *env))
	if err != nil {
		log.Fatal(err)
		return
	}

	goth.UseProviders(
		github.New(os.Getenv("GITHUB_CLIENT_KEY"), os.Getenv("GITHUB_SECRET"), os.Getenv("GITHUB_CALLBACK")),
	)

	p := pat.New()

	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	p.Add("GET", "/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	p.Add("GET", "/login", &templateHandler{filename: "login.html"})
	p.Get("/auth/{action}/{provider}", loginHandler)
	p.Add("GET", "/room", r)

	// チャットルームの開始
	go r.run()
	// Webサーバの起動
	log.Println("Webサーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, p); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
示例#20
0
文件: teppan.go 项目: dtan4/teppan
func main() {
	var (
		base64Encode bool
	)

	if len(os.Args) != 2 && len(os.Args) != 3 {
		fmt.Fprintln(os.Stderr, Usage)
		os.Exit(1)
	}

	flag.BoolVar(&base64Encode, "base64", false, "Embed Base64-encoded variables")
	flag.Parse()

	err := godotenv.Load()
	if err != nil {
		fmt.Fprintln(os.Stderr, "Failed to load .env!")
		os.Exit(1)
	}

	templateFile := os.Args[len(os.Args)-1]
	tmpl, err := template.ParseFiles(templateFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to parse template file: %s\n", templateFile)
		os.Exit(1)
	}

	err = tmpl.Execute(os.Stdout, envmap(base64Encode))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to apply from template file: %s\n", templateFile)
		os.Exit(1)
	}
}
示例#21
0
func run(c *cli.Context) error {
	if c.String("env-file") != "" {
		_ = godotenv.Load(c.String("env-file"))
	}

	plugin := Plugin{
		Key:                    c.String("access-key"),
		Secret:                 c.String("secret-key"),
		Bucket:                 c.String("bucket"),
		Region:                 c.String("region"),
		Source:                 c.String("source"),
		Target:                 c.String("target"),
		Delete:                 c.Bool("delete"),
		Access:                 c.Generic("access").(*StringMapFlag).Get(),
		CacheControl:           c.Generic("cache-control").(*StringMapFlag).Get(),
		ContentType:            c.Generic("content-type").(*StringMapFlag).Get(),
		ContentEncoding:        c.Generic("content-encoding").(*StringMapFlag).Get(),
		Metadata:               c.Generic("metadata").(*DeepStringMapFlag).Get(),
		Redirects:              c.Generic("redirects").(*MapFlag).Get(),
		CloudFrontDistribution: c.String("cloudfront-distribution"),
		DryRun:                 c.Bool("dry-run"),
	}

	return plugin.Exec()
}
示例#22
0
func fetchMembers() []Member {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	meetupGroupId := os.Getenv("MEETUP_GROUP_ID")
	meetupApiKey := os.Getenv("MEETUP_API_KEY")
	reqUrl := fmt.Sprintf(meetupApiUrl, meetupGroupId, meetupApiKey)
	client := &http.Client{}
	fmt.Println("API Request URL: ", reqUrl)
	req, reqErr := http.NewRequest("GET", reqUrl, nil)
	if reqErr != nil {
		log.Fatal("NewRequest: ", reqErr)
		return nil
	}
	resp, respErr := client.Do(req)
	if respErr != nil {
		log.Fatal("Do: ", respErr)
		return nil
	}
	defer resp.Body.Close()
	body, dataReadErr := ioutil.ReadAll(resp.Body)
	if dataReadErr != nil {
		log.Fatal("ReadAll: ", dataReadErr)
		return nil
	}
	var results MemberResult
	errr := json.Unmarshal(body, &results)
	if errr != nil {
		log.Fatal(errr)
	}
	return results.Results
}
示例#23
0
func LoadEnv(loadDB bool) {
	godotenv.Load(Env)
	config.CheckEnv()

	if loadDB {
		db = config.NewDB()
	}
}
示例#24
0
func LoadEnvironment() {
	// load .env
	flag.StringVar(&envFilePath, "env_path", WorkingDirectory()+"/.env", "Sets path for .env config")
	flag.Parse()
	if err := godotenv.Load(envFilePath); err != nil {
		log.Fatalf("Error loading .env file: %s", err.Error())
	}
}
示例#25
0
文件: main.go 项目: mono0x/my-scraper
func main() {
	log.SetFlags(log.Lshortfile)

	_ = godotenv.Load()

	if err := run(); err != nil {
		log.Fatal(err)
	}
}
示例#26
0
文件: api.go 项目: hek/go-api-starter
func main() {
	if err := godotenv.Load(); err != nil {
		panic(err)
	}

	api := echo.New(){hek:go-api:staticEndpoint}
	api.Get("{hek:go-api:rootEndpoint}", Hi)
	api.Run(standard.New(os.Getenv("ADDR")))
}
示例#27
0
func main() {
	godotenv.Load()
	org := os.Getenv("GITHUB_ORGANIZATION")
	repo := os.Getenv("GITHUB_REPO")
	team := os.Getenv("GITHUB_TEAM")
	token := os.Getenv("GITHUB_ACCESS_TOKEN")

	var opts Options
	p := flags.NewParser(&opts, flags.Default)
	_, err := p.ParseArgs(os.Args[1:])
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}
	d := NewDice(strings.Split(opts.ExemptedUsers, ","))
	im := NewIssueManager(org, repo, team, token, opts.DryRun)

	issues, err := im.FindIssues(opts.Query)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	assinedNumber := 0
	for _, issue := range issues {
		if im.IsAlreadyAssignedExpectAuthor(issue) {
			continue
		}
		reviewers, err := im.FindCandidatesOfReviewers(issue)
		if err != nil {
			log.Fatal(err)
			continue
		}
		if opts.Debug {
			log.Println(fmt.Sprintf("Candidates are %s", reviewers))
		}
		assignee := d.Throw(reviewers)

		_, err = im.Assign(issue, assignee, opts.AssignAuthor)
		if err != nil {
			log.Fatal(err)
			continue
		}

		if len(opts.Comment) > 0 && opts.DryRun == false {
			im.Comment(issue, opts.Comment+"@"+assignee)
		}

		assinedNumber++
		if opts.Debug {
			log.Println(fmt.Sprintf("#%d %s %s => author:%s assigned:%s", *issue.Number, *issue.HTMLURL, *issue.Title, *issue.User.Login, assignee))
		}
		if opts.Limit > 0 && opts.Limit <= assinedNumber {
			break
		}
	}
}
示例#28
0
文件: main.go 项目: amacneil/dbmate
func loadDotEnv() {
	if _, err := os.Stat(".env"); err != nil {
		return
	}

	if err := godotenv.Load(); err != nil {
		log.Fatal("Error loading .env file")
	}
}
示例#29
0
文件: main.go 项目: nullstyle/mcdev
// Load loads the current directory's .env file into the current process
// provided the `env` flag is true.
func Load() {
	if !*env {
		return
	}

	if err := godotenv.Load(); err != nil {
		log.Printf("warn: %v", err)
	}
}
示例#30
0
func TestGoKeen(t *testing.T) {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	RegisterFailHandler(Fail)
	RunSpecs(t, "GoKeen Suite")
}