• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang envdecode.Decode函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/joeshaw/envdecode.Decode函数的典型用法代码示例。如果您正苦于以下问题:Golang Decode函数的具体用法?Golang Decode怎么用?Golang Decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Decode函数的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	var conf Conf
	err := envdecode.Decode(&conf)
	if err != nil {
		log.Fatal(err)
	}

	stripe.Key = conf.StripeKey
	//stripe.LogLevel = 1 // errors only

	producer, err := sarama.NewSyncProducer(strings.Split(conf.SeedBroker, ","), nil)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := producer.Close(); err != nil {
			log.Fatal(err)
		}
	}()

	log.Printf("Tailing the log")
	err = tailLog(producer, conf.KafkaTopic)
	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:brandur,项目名称:stripe-warehouse,代码行数:26,代码来源:main.go


示例2: main

func main() {
	var api struct {
		Key string `env:"GOOGLE_PLACES_API_KEY,required"`
	}
	if err := envdecode.Decode(&api); err != nil {
		log.Fatalln(err)
	}
	meander.APIKey = api.Key
	http.HandleFunc("/journeys", cors(func(w http.ResponseWriter, r *http.Request) {
		respond(w, r, meander.Journeys)
	}))
	http.HandleFunc("/recommendations", cors(func(w http.ResponseWriter, r *http.Request) {
		q := &meander.Query{
			Journey: strings.Split(r.URL.Query().Get("journey"), "|"),
		}
		q.Lat, _ = strconv.ParseFloat(r.URL.Query().Get("lat"), 64)
		q.Lng, _ = strconv.ParseFloat(r.URL.Query().Get("lng"), 64)
		q.Radius, _ = strconv.Atoi(r.URL.Query().Get("radius"))
		q.CostRangeStr = r.URL.Query().Get("cost")
		places := q.Run()
		respond(w, r, places)
	}))
	http.ListenAndServe(":8080", http.DefaultServeMux)

}
开发者ID:upamune,项目名称:meander,代码行数:25,代码来源:main.go


示例3: New

// New creates a new SparkClient to be used.
// s := sparkClient.New()
// s.Rooms()
// requires that the environment variable: "SPARK_AUTH_TOKEN" be defined
func New() *SparkClient {
	var conn net.Conn
	var r io.ReadCloser

	var conf struct {
		AuthToken string `env:"SPARK_AUTH_TOKEN"`
	}

	if err := envdecode.Decode(&conf); err != nil {
		log.Fatalln(err)
	}
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				if conn != nil {
					conn.Close()
					conn = nil
				}
				netc, err := net.DialTimeout(netw, addr, 5*time.Second)
				if err != nil {
					return nil, err
				}
				conn = netc
				return netc, nil
			},
		},
	}

	return &SparkClient{
		authtoken:  conf.AuthToken,
		conn:       conn,
		httpClient: client,
		reader:     r,
	}
}
开发者ID:jschweizer78,项目名称:gospark,代码行数:39,代码来源:sparkClient.go


示例4: setupTwitterAuth

//执行认证
func setupTwitterAuth() {

	var ts struct {
		ConsumerKey    string `env:"SP_TWITTER_KEY,required"`
		ConsumerSecret string `env:"SP_TWITTER_SECRET,required"`
		AccessToken    string `env:"SP_TWITTER_ACCESSTOKEN,required"`
		AccessSecret   string `env:"SP_TWITTER_ACCESSSECRET,required"`
	}

	//envdecode 解析获取 环境变量
	if err := envdecode.Decode(&ts); err != nil {
		log.Fatalln(err)
	}

	creds = &oauth.Credentials{
		Token:  ts.AccessToken,
		Secret: ts.AccessSecret,
	}

	authClient = &oauth.Client{
		Credentials: oauth.Credentials{
			Token:  ts.ConsumerKey,
			Secret: ts.ConsumerSecret,
		},
	}
}
开发者ID:oywc410,项目名称:MYPG,代码行数:27,代码来源:twitter.go


示例5: Load

func Load() (*Config, error) {
	conf := &Config{}
	err := envdecode.Decode(conf)
	if err != nil {
		return nil, err
	}

	conf.JQVer = jq.Version

	return conf, nil
}
开发者ID:jingweno,项目名称:jqplay,代码行数:11,代码来源:config.go


示例6: New

func New() *TwitStream {
	var ts struct {
		ConsumerKey    string `env:"STRIPSTOCK_TWITTER_CONSUMER_KEY,required"`
		ConsumerSecret string `env:"STRIPSTOCK_TWITTER_CONSUMER_SECRET,required"`
		AccessToken    string `env:"STRIPSTOCK_TWITTER_ACCESS_TOKEN,required"`
		AccessSecret   string `env:"STRIPSTOCK_TWITTER_ACCESS_SECRET,required"`
	}
	var conn net.Conn

	if err := envdecode.Decode(&ts); err != nil {
		log.Fatalln(err)
	}
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				if conn != nil {
					conn.Close()
					conn = nil
				}
				netc, err := net.DialTimeout(netw, addr, 5*time.Second)
				if err != nil {
					return nil, err
				}
				conn = netc
				return netc, nil
			},
		},
	}

	var r io.ReadCloser

	return &TwitStream{
		authClient: &oauth.Client{
			Credentials: oauth.Credentials{
				Token:  ts.ConsumerKey,
				Secret: ts.ConsumerSecret,
			},
		},
		creds: &oauth.Credentials{
			Token:  ts.AccessToken,
			Secret: ts.AccessSecret,
		},
		conn:       conn,
		httpClient: client,
		reader:     r,
	}
}
开发者ID:vallard,项目名称:twitter-client,代码行数:47,代码来源:twitstream.go


示例7: main

func main() {
	singularity.InitLog(false)

	err := envdecode.Decode(&conf)
	if err != nil {
		log.Fatal(err)
	}

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

	err = serve(conf.Port)
	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:brandur,项目名称:singularity,代码行数:18,代码来源:main.go


示例8: dbSession

func dbSession() dropbox.Session {
	var s struct {
		AppKey      string `env:"DROPBOX_APP_KEY,required"`
		AppSecret   string `env:"DROPBOX_APP_SECRET,required"`
		TokenKey    string `env:"DROPBOX_TOKEN_KEY,required"`
		TokenSecret string `env:"DROPBOX_TOKEN_SECRET,required"`
	}
	if err := envdecode.Decode(&s); err != nil {
		log.Fatalln(err)
	}

	return dropbox.Session{
		AppKey:     s.AppKey,
		AppSecret:  s.AppSecret,
		AccessType: "full_dropbox",
		Token: dropbox.AccessToken{
			Key:    s.TokenKey,
			Secret: s.TokenSecret,
		},
	}
}
开发者ID:dmikalova,项目名称:dropup,代码行数:21,代码来源:dropup.go


示例9: setupTwitterAuth

func setupTwitterAuth() {
	// github.com/joeshaw/envdecodeでDecodeできる形式
	var ts struct {
		ConsumerKey    string `env:"SOCIAL_POLL_TWITTER_KEY,required"`
		ConsumerSecret string `env:"SOCIAL_POLL_TWITTER_SECRET,required"`
		AccessToken    string `env:"SOCIAL_POLL_TWITTER_ACCESS_TOKEN,required"`
		AccessSecret   string `env:"SOCIAL_POLL_TWITTER_ACCESS_SECRET,required"`
	}

	if err := envdecode.Decode(&ts); err != nil {
		log.Fatalln(err)
	}
	creds = &oauth.Credentials{
		Token:  ts.AccessToken,
		Secret: ts.AccessSecret,
	}
	authClient = &oauth.Client{
		Credentials: oauth.Credentials{
			Token:  ts.ConsumerKey,
			Secret: ts.ConsumerSecret,
		},
	}
}
开发者ID:keiwt,项目名称:goblueprints,代码行数:23,代码来源:twitter.go


示例10: setupTwitterAuth

func setupTwitterAuth() {
	// we don't need to use the type elsewhere,
	// we define it inline as a anonymous type
	var ts struct {
		ConsumerKey    string `env:"SP_TWITTER_KEY,required"`
		ConsumerSecret string `env:"SP_TWITTER_SECRET,required"`
		AccessToken    string `env:"SP_TWITTER_ACCESSTOKEN,required"`
		AcessSecret    string `env:"SP_TWITTER_ACCESSSECRET,required"`
	}
	if err := envdecode.Decode(&ts); err != nil {
		log.Fatalln(err)
	}
	creds = &oauth.Credentials{
		Token:  ts.AccessToken,
		Secret: ts.AcessSecret,
	}
	authClient = &oauth.Client{
		Credentials: oauth.Credentials{
			Token:  ts.ConsumerKey,
			Secret: ts.ConsumerSecret,
		},
	}
}
开发者ID:liyu-wang,项目名称:go-socialpoll,代码行数:23,代码来源:twitter.go


示例11: NewIssConfig

func NewIssConfig() (IssConfig, error) {
	config := IssConfig{}

	err := envdecode.Decode(&config)
	if err != nil {
		return config, err
	}

	if config.PemFile != "" {
		pemFileData, err := ioutil.ReadFile(config.PemFile)
		if err != nil {
			return config, fmt.Errorf("Unable to read pemfile: %s", err)
		}

		cp := x509.NewCertPool()
		if ok := cp.AppendCertsFromPEM(pemFileData); !ok {
			return config, fmt.Errorf("Error parsing PEM: %s", config.PemFile)
		}

		config.TlsConfig = &tls.Config{RootCAs: cp}
	}

	sp := make([]string, 0, 2)
	if config.LibratoSource != "" {
		sp = append(sp, config.LibratoSource)
	}
	if config.Dyno != "" {
		sp = append(sp, config.Dyno)
	}

	config.LibratoSource = strings.Join(sp, ".")

	config.MetricsRegistry = metrics.NewRegistry()

	return config, nil
}
开发者ID:heroku,项目名称:log-iss,代码行数:36,代码来源:config.go


示例12: readConf

func readConf() {
	err := envdecode.Decode(&conf)
	if err != nil {
		log.Fatal(err.Error())
	}
}
开发者ID:brandur,项目名称:certrotate,代码行数:6,代码来源:main.go


示例13: main

func main() {
	var ts struct {
		ConsumerKey    string `env:"SP_TWITTER_KEY,required"`
		ConsumerSecret string `env:"SP_TWITTER_SECRET,required"`
		AccessToken    string `env:"SP_TWITTER_ACCESSTOKEN,required"`
		AccessSecret   string `env:"SP_TWITTER_ACCESSSECRET,required"`
	}
	if err := envdecode.Decode(&ts); err != nil {
		log.Fatalln(err)
	}
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				if conn != nil {
					conn.Close()
					conn = nil
				}
				netc, err := net.DialTimeout(netw, addr, 5*time.Second)
				if err != nil {
					return nil, err
				}
				conn = netc
				return netc, nil
			},
		},
	}
	creds = &oauth.Credentials{
		Token:  ts.AccessToken,
		Secret: ts.AccessSecret,
	}
	authClient = &oauth.Client{
		Credentials: oauth.Credentials{
			Token:  ts.ConsumerKey,
			Secret: ts.ConsumerSecret,
		},
	}
	twitterStopChan := make(chan struct{}, 1)
	publisherStopChan := make(chan struct{}, 1)
	stop := false
	signalChan := make(chan os.Signal, 1)
	go func() {
		<-signalChan
		stop = true
		log.Println("Stopping...")
		closeConn()
	}()
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
	votes := make(chan string) // chan for votes
	go func() {
		pub, _ := nsq.NewProducer("localhost:4150", nsq.NewConfig())
		for vote := range votes {
			pub.Publish("votes", []byte(vote)) // publish vote
		}
		log.Println("Publisher: Stopping")
		pub.Stop()
		log.Println("Publisher: Stopped")
		publisherStopChan <- struct{}{}
	}()
	go func() {
		defer func() {
			twitterStopChan <- struct{}{}
		}()
		for {
			if stop {
				log.Println("Twitter: Stopped")
				return
			}
			time.Sleep(2 * time.Second) // calm
			var options []string
			db, err := mgo.Dial("localhost")
			if err != nil {
				log.Fatalln(err)
			}
			iter := db.DB("ballots").C("polls").Find(nil).Iter()
			var p poll
			for iter.Next(&p) {
				options = append(options, p.Options...)
			}
			iter.Close()
			db.Close()

			hashtags := make([]string, len(options))
			for i := range options {
				hashtags[i] = "#" + strings.ToLower(options[i])
			}

			form := url.Values{"track": {strings.Join(hashtags, ",")}}
			formEnc := form.Encode()

			u, _ := url.Parse("https://stream.twitter.com/1.1/statuses/filter.json")
			req, err := http.NewRequest("POST", u.String(), strings.NewReader(formEnc))
			if err != nil {
				log.Println("creating filter request failed:", err)
			}
			req.Header.Set("Authorization", authClient.AuthorizationHeader(creds, "POST", u, form))
			req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			req.Header.Set("Content-Length", strconv.Itoa(len(formEnc)))

			resp, err := client.Do(req)
			if err != nil {
//.........这里部分代码省略.........
开发者ID:yanai-masahiro,项目名称:goblueprints,代码行数:101,代码来源:main.go


示例14: main

func main() {
	var conf Conf
	err := envdecode.Decode(&conf)
	if err != nil {
		log.Fatal(err.Error())
	}

	client := wgt2.GetSpotifyClient(conf.ClientID, conf.ClientSecret, conf.RefreshToken)

	db, err := wgt2.LoadDatabase(DBFilename)
	if err != nil {
		log.Fatal(err.Error())
	}

	for _, rawArtist := range db.RawArtists.Data {
		dbArtist := db.Artists.GetArtistByWGTName(rawArtist.WGTName)
		if dbArtist != nil {
			log.Printf("Have artist already: %v", dbArtist.Name)
			continue
		}

		searchName := rawArtist.WGTName
		if val, ok := ManualOverrides[searchName]; ok {
			if val == "" {
				log.Printf("Skipping '%v' due to override", searchName)
				continue
			}

			log.Printf("Using manual override '%v' for '%v'", val, searchName)
			searchName = val
		}

		res, err := client.Search(searchName, spotify.SearchTypeArtist)
		if err != nil {
			log.Fatal(err.Error())
		}

		if len(res.Artists.Artists) < 1 {
			log.Printf("Artist not found: %v", rawArtist.WGTName)
			continue
		}

		artist := res.Artists.Artists[0]

		dbArtist = &wgt2.Artist{
			Genres:     artist.Genres,
			ID:         string(artist.ID),
			Name:       artist.Name,
			Popularity: artist.Popularity,
			URI:        string(artist.URI),
			WGTName:    rawArtist.WGTName,
		}

		log.Printf("Found artist: %v (from: %v; popularity: %v/100)",
			artist.Name, rawArtist.WGTName, artist.Popularity)

		tracks, err := client.GetArtistsTopTracks(artist.ID, "US")
		if err != nil {
			log.Fatal(err.Error())
		}

		for _, track := range tracks {
			dbTrack := wgt2.Track{
				ID:         string(track.ID),
				Name:       track.Name,
				Popularity: track.Popularity,
				URI:        string(track.URI),
			}
			dbArtist.TopTracks = append(dbArtist.TopTracks, dbTrack)
		}

		db.Artists.AddArtist(dbArtist)
	}

	err = db.Save()
	if err != nil {
		log.Fatal(err.Error())
	}
}
开发者ID:brandur,项目名称:wgt2,代码行数:79,代码来源:main.go


示例15: newConfFromEnv

// Loads configuration from the process' environment.
func newConfFromEnv() (*Conf, error) {
	conf := &Conf{}
	err := envdecode.Decode(conf)
	return conf, err
}
开发者ID:brandur,项目名称:spaced,代码行数:6,代码来源:main.go


示例16: main

func main() {
	// We require each program to have endpoints defined.
	var params struct {
		Endpoints   string `env:"SP_ENDPOINTS,required"`
		Credentials string `env:"SP_ENDPOINT_CREDENTIALS,required"`
	}

	if err := envdecode.Decode(&params); err != nil {
		log.Fatalln(err)
	}

	endpoints := strings.Split(params.Endpoints, ",")
	creds := strings.Split(params.Credentials, ",")
	if len(endpoints) != len(creds) {
		log.Fatal("Each endpoint should have a corresponding credential")
	}

	// All the OIDs we'll snmp walk through to get
	oidWork := map[string]string{
		".1.3.6.1.2.1.1.5":         "sysName",
		".1.3.6.1.2.1.2.2.1.2":     "name",
		".1.3.6.1.2.1.2.2.1.10":    "ifInOctets",
		".1.3.6.1.2.1.2.2.1.16":    "ifOutOctets",
		".1.3.6.1.2.1.31.1.1.1.6":  "ifHCInOctets",
		".1.3.6.1.2.1.31.1.1.1.10": "ifHCOutOctets",
		".1.3.6.1.2.1.31.1.1.1.15": "ifHighSpeed",
	}

	// all the commands we walk through NXAPI to get.
	nxapiWork := map[string]string{
		"show version":            "version",
		"show interface counters": "counters",
	}

	// The main waitgroup for each switch waits for
	// each switch to finish its job.
	var mainWg sync.WaitGroup
	// The array of waitgroups are the jobs that each
	// switch must proccess.
	wg := make([]sync.WaitGroup, len(endpoints))

	// we will run in a continuous loop forever!
	// or at least until the user hits ctrl-c or we get a signal interrupt.
	stop := false
	signalChan := make(chan os.Signal, 1)
	interruptChan := make(chan struct{}, 1)
	go func() {
		<-signalChan
		stop = true
		log.Println("Cleaning up...")
		// send stuff to the channel so that it closes.  That way we don't have to wait so long.
		interruptChan <- struct{}{}
	}()
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

	for {

		if stop {
			break
		}
		// make sure we wait for each of the switches
		mainWg.Add(len(endpoints))

		// go through each device and grab the counters.
		for i, endpoint := range endpoints {
			// figure out which method to run:
			em := strings.Split(endpoint, ":")
			if len(em) < 2 {
				fmt.Println("Invalid input: ", endpoint)
				fmt.Println("please export SP_ENDPOINTS=<name>:<method> where method is SNMP or NXAPI")
				// don't wait for me any more.
				mainWg.Add(-1)
				// go to the next switch
				continue
			}
			/* big map:
			server {
				interface {
					key : value
				}
			}
			*/
			m := make(map[string]map[string]map[string]string)
			if em[1] == "SNMP" {
				go func(e string, c string, w sync.WaitGroup) {
					defer mainWg.Done()
					// mapping hash table for interface names.
					w.Add(len(oidWork))
					// concurrently execute all of the snmp walks
					for oid, name := range oidWork {
						go func(o string, n string) {
							defer w.Done()
							walkValue(e, c, o, n, m)
						}(oid, name)
					}
					w.Wait()
					processCollectedSNMPData(m[e])
				}(em[0], creds[i], wg[i])
			} else if em[1] == "NXAPI" {
				// Yes.. this is hard to process, so let's walk through this.
//.........这里部分代码省略.........
开发者ID:vallard,项目名称:stickypipe-agent,代码行数:101,代码来源:main.go


示例17: main

func main() {
	var params struct {
		Endpoints   string `env:"SP_ENDPOINTS,required"`
		Credentials string `env:"SP_ENDPOINT_CREDENTIALS,required"`
	}

	if err := envdecode.Decode(&params); err != nil {
		log.Fatalln(err)
	}

	endpoints := strings.Split(params.Endpoints, ",")
	// creds should be of the form: user:password,user:password
	cred := strings.Split(params.Credentials, ",")
	if len(endpoints) != len(cred) {
		log.Fatal("Each endpoint should have a corresponding credential")
	}

	for i, ep := range endpoints {
		up := strings.Split(cred[i], ":")
		if len(up) < 2 {
			log.Fatal("Credentials must be of form user:password")
			break
		}
		var jsonStr = []byte(`{
			"ins_api": {
					"version":       "1.0",
					"type":          "cli_show",
					"chunk":         "0",
					"sid":           "1",
					"input":         "sh interface counters",
					"output_format": "json",
				}
			}
				`)
		req, err := http.NewRequest("POST", "http://"+ep+"/ins", bytes.NewBuffer(jsonStr))
		if err != nil {
			log.Println("HTTP Post: ", err)
		}

		req.Header.Set("content-type", "application/json")
		req.SetBasicAuth(up[0], up[1])

		client := &http.Client{}
		resp, err := client.Do(req)
		if err != nil {
			log.Fatal("response error: ", err)
		}
		defer resp.Body.Close()

		fmt.Println("response Status: ", resp.Status)
		fmt.Println("response Headers: ", resp.Header)
		body, err := ioutil.ReadAll(resp.Body)
		//rr := make(map[string]interface{})
		rr := ins_api{}
		err = json.Unmarshal(body, &rr)
		if err != nil {
			log.Fatal("Error unmarshalling: ", err)
		}
		//fmt.Println("responseBody:", string(body))

		fmt.Println(rr)
	}

	log.Println("End of program")
}
开发者ID:vallard,项目名称:stickypipe-agent,代码行数:65,代码来源:nxagent.go



注:本文中的github.com/joeshaw/envdecode.Decode函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang multierror.Errors类代码示例发布时间:2022-05-23
下一篇:
Golang eventual2go.StreamController类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap