当前位置: 首页>>代码示例>>Golang>>正文


Golang to.String函数代码示例

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


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

示例1: init

func init() {
	gob.Register(UserModel{})

	// Load config file
	conf, err := yaml.Open("config.yml")
	if err != nil {
		log.Fatal(err)
	}

	// Retrieve credentials from config file
	username := to.String(conf.Get("database", "username"))
	password := to.String(conf.Get("database", "password"))
	name := to.String(conf.Get("database", "name"))

	// Open mysql connection
	dsn := fmt.Sprintf("%s:%[email protected]/%s?%s", username, password, name, "parseTime=true")
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}

	// Sets the maximum number of connections in the idle connection pool
	db.SetMaxIdleConns(100)

}
开发者ID:jonahgeorge,项目名称:jobgenius,代码行数:25,代码来源:init.go

示例2: SaveDNS

func (db *database) SaveDNS(dns DNS) error {
	config := to.String(dns.Configuration())
	state := to.String(dns.State())
	err := db.storage.Set(configurationKeyForDNSName(dns.Name()), []byte(config))
	if err != nil {
		return err
	}

	return db.storage.Set(stateKeyForDNSName(dns.Name()), []byte(state))
}
开发者ID:tjbx,项目名称:X10Bridge,代码行数:10,代码来源:database.go

示例3: configureSenders

func configureSenders() error {
	sendersList, ok := config.GetInterface("notifier", "senders").([]interface{})
	if ok == false {
		return fmt.Errorf("Failed parse senders")
	}
	for _, senderSettingsI := range sendersList {
		senderSettings := make(map[string]string)
		for k, v := range senderSettingsI.(map[interface{}]interface{}) {
			senderSettings[to.String(k)] = to.String(v)
		}
		senderSettings["front_uri"] = config.Get("front", "uri")
		switch senderSettings["type"] {
		case "pushover":
			if err := notifier.RegisterSender(senderSettings, &pushover.Sender{}); err != nil {
				log.Fatalf("Can not register sender %s: %s", senderSettings["type"], err)
			}
		case "slack":
			if err := notifier.RegisterSender(senderSettings, &slack.Sender{}); err != nil {
				log.Fatalf("Can not register sender %s: %s", senderSettings["type"], err)
			}
		case "mail":
			if err := notifier.RegisterSender(senderSettings, &mail.Sender{}); err != nil {
				log.Fatalf("Can not register sender %s: %s", senderSettings["type"], err)
			}
		case "script":
			if err := notifier.RegisterSender(senderSettings, &script.Sender{}); err != nil {
				log.Fatalf("Can not register sender %s: %s", senderSettings["type"], err)
			}
		case "telegram":
			if err := notifier.RegisterSender(senderSettings, &telegram.Sender{}); err != nil {
				log.Fatalf("Can not register sender %s: %s", senderSettings["type"], err)
			}
		case "twilio sms":
			if err := notifier.RegisterSender(senderSettings, &twilio.Sender{}); err != nil {
				log.Fatalf("Can not register sender %s: %s", senderSettings["type"], err)
			}
		case "twilio voice":
			if err := notifier.RegisterSender(senderSettings, &twilio.Sender{}); err != nil {
				log.Fatalf("Can not register sender %s: %s", senderSettings["type"], err)
			}
		// case "email":
		// 	if err := notifier.RegisterSender(senderSettings, &kontur.MailSender{}); err != nil {
		// 	}
		// case "phone":
		// 	if err := notifier.RegisterSender(senderSettings, &kontur.SmsSender{}); err != nil {
		// 	}
		default:
			return fmt.Errorf("Unknown sender type [%s]", senderSettings["type"])
		}
	}
	return nil
}
开发者ID:tantra35,项目名称:notifier,代码行数:52,代码来源:main.go

示例4: Generate

// options:
//  url - url to generate codes from
//  notmog - turn off grabbing transmogged items from armory
func (g *Generator) Generate(options map[string]interface{}, w io.Writer) error {
	url := to.String(options["url"])
	var tmorphItems TMorphItems
	var err error
	switch {
	case strings.Contains(url, "wowhead.com"):
		tmorphItems, err = wowhead(options)
	case strings.Contains(url, "battle.net/wow"):
		tmorphItems, err = wowarmory(options)
	case strings.Contains(url, "http"):
		tmorphItems, err = generic(options)
	default:
		return errors.New("Do not recognize the URL.")
	}

	if err != nil {
		return err
	}

	g.lastTmorphItems = tmorphItems
	bonus := int(to.Int64(options["bonus"]))
	g.Bonus(bonus)
	g.Output(w)

	return nil
}
开发者ID:kdar,项目名称:morphgen,代码行数:29,代码来源:morph.go

示例5: generic

// Attempt to find any links in the page that we can
// parse and generate codes for.
func generic(options map[string]interface{}) (TMorphItems, error) {
	resp, err := http.Get(to.String(options["url"]))
	if err != nil {
		return nil, err
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	resp.Body.Close()

	matches := wowheadUrlRe.FindAllStringSubmatch(string(data), -1)
	var items []string
	for _, match := range matches {
		items = append(items, match[1])
	}

	matches = wowdbUrlRe.FindAllStringSubmatch(string(data), -1)
	for _, match := range matches {
		items = append(items, match[1])
	}

	//options["url"] = wowheadUrl + strings.Join(items, ";")
	//return wowhead(options)
	return wowapi(items)
}
开发者ID:kdar,项目名称:morphgen,代码行数:29,代码来源:generic.go

示例6: main

func main() {
	// intialize routes muxer
	r := mux.NewRouter()

	// article routes
	r.HandleFunc("/articles", ArticleController{}.Index()).Methods("GET")
	r.HandleFunc("/articles", ArticleController{}.Create()).Methods("POST")
	r.HandleFunc("/articles/new", ArticleController{}.Form()).Methods("GET")
	r.HandleFunc("/articles/{id:[0-9]+}", ArticleController{}.Retrieve()).Methods("GET")
	r.HandleFunc("/articles/{id:[0-9]+}/publish", ArticleController{}.Publish()).Methods("POST")
	r.HandleFunc("/articles/{id:[0-9]+}/edit", ArticleController{}.Edit()).Methods("GET")
	r.HandleFunc("/articles/{id:[0-9]+}/delete", ArticleController{}.Delete()).Methods("POST")

	// interview routes
	r.HandleFunc("/interviews", InterviewController{}.Index()).Methods("GET")
	r.HandleFunc("/interviews/{id:[0-9]+}", InterviewController{}.Retrieve()).Methods("GET")
	r.HandleFunc("/interviews/new", InterviewController{}.Form()).Methods("GET")
	r.HandleFunc("/interviews/new", InterviewController{}.Create()).Methods("POST")

	// account routes
	r.HandleFunc("/accounts", UserController{}.Index())
	r.HandleFunc("/accounts/{id:[0-9]+}", UserController{}.Retrieve())

	// static page routes
	r.HandleFunc("/about", MainController{}.About())
	r.HandleFunc("/terms", MainController{}.Terms())
	r.HandleFunc("/privacy", MainController{}.Privacy())
	r.HandleFunc("/", MainController{}.Landing())

	// user routes
	r.HandleFunc("/signin", UserController{}.SignInForm()).Methods("GET")
	r.HandleFunc("/signin", UserController{}.SignInApi()).Methods("POST")
	r.HandleFunc("/signout", UserController{}.SignOut()).Methods("GET")
	r.HandleFunc("/signup", UserController{}.SignUpForm()).Methods("GET")
	r.HandleFunc("/signup", UserController{}.SignUpApi()).Methods("POST")

	// api routes
	r.HandleFunc("/api/charts/groupwork", Chart{}.GroupWork())
	r.HandleFunc("/api/charts/fulfillment", Chart{}.Fulfillment())
	r.HandleFunc("/api/charts/breakdown", Chart{}.Breakdown())

	// static resource files
	http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
	http.Handle("/vendor/", http.StripPrefix("/vendor/", http.FileServer(http.Dir("vendor"))))

	// register gorrilla router as root
	http.Handle("/", r)

	// Load config file
	conf, err := yaml.Open("config.yml")
	if err != nil {
		log.Fatal(err)
	}

	port := to.String(conf.Get("server", "port"))
	if err = http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}
开发者ID:jonahgeorge,项目名称:jobgenius,代码行数:59,代码来源:main.go

示例7: Resize

func (self *Image) Resize(size string) {
	var err error

	url := to.String(self.Params.Get("url"))

	relPath := ImageRoot + tango.PS + size + tango.PS + checksum.String(fmt.Sprintf("%s/%s", size, url), crypto.SHA1) + ".png"
	fullPath := Root + tango.PS + relPath

	_, err = os.Stat(fullPath)

	if err == nil {

		app.Server.Context.Redirect("/" + relPath)

		app.Server.Context.HttpError(200)

		return

	} else {

		filePath, err := resource.Download(url)

		if err == nil {

			thumb := canvas.New()

			opened := thumb.Open(filePath)

			if opened == true {

				resize := strings.Split(size, "x")

				width, _ := strconv.Atoi(resize[0])
				height, _ := strconv.Atoi(resize[1])

				thumb.AutoOrientate()
				thumb.Thumbnail(uint(width), uint(height))

				os.MkdirAll(path.Dir(fullPath), os.ModeDir|0755)

				written := thumb.Write(fullPath)

				if written {
					app.Server.Context.Redirect("/" + relPath)
				} else {
					app.Server.Context.HttpError(500)
				}

				return
			}

		}

	}

	app.Server.Context.HttpError(404)
}
开发者ID:astrata,项目名称:tango-doc,代码行数:57,代码来源:image.go

示例8: TestToken

func TestToken(t *testing.T) {
	yf, err := yaml.Open("settings.yaml")

	client = New()

	if err == nil {
		client.SetAccessToken(to.String(yf.Get("providers", "instagram", "access_token")))
	}
}
开发者ID:xiam,项目名称:instagram,代码行数:9,代码来源:instagram_test.go

示例9: Run

// Starts a fastcgi/http server.
func (server *Server) Run() error {

	var err error

	server.serveMux.Handle("/", server)

	domain := "unix"
	addr := to.String(config.Get("server/socket"))

	if addr == "" {
		domain = "tcp"
		addr = fmt.Sprintf("%s:%d", to.String(config.Get("server/bind")), to.Int(config.Get("server/port")))
	}

	server.listener, err = net.Listen(domain, addr)

	if err != nil {
		log.Fatalf("Failed to bind on %s: %s", addr, err.Error())
	}

	defer server.listener.Close()

	log.Printf("%s is ready to dance.\n", server.listener.Addr())
	log.Printf("Stop server with ^C.\n")

	fmt.Fprintf(os.Stderr, "\n")

	switch to.String(config.Get("server/type")) {
	case "fastcgi":
		if err == nil {
			fcgi.Serve(server.listener, server.serveMux)
		} else {
			log.Fatalf("Failed to start FastCGI server.")
		}
	default:
		if err == nil {
			http.Serve(server.listener, server.serveMux)
		} else {
			log.Fatalf("Failed to start HTTP server.")
		}
	}

	return nil
}
开发者ID:astrata,项目名称:tango,代码行数:45,代码来源:server.go

示例10: encodeParams

func encodeParams(params map[string]interface{}) (string, error) {
	if len(params) > 0 {
		values := url.Values{}
		for key, value := range params {
			values.Add(key, to.String(value))
		}
		return values.Encode(), nil
	}
	return "", errors.New("Params Is Empty!")
}
开发者ID:hiproz,项目名称:weigo,代码行数:10,代码来源:weibo.go

示例11: init

func init() {
	// Load config file
	conf, err := yaml.Open("config.yml")
	if err != nil {
		log.Fatal(err)
	}

	// Retrieve credentials from config file
	username := to.String(conf.Get("database", "username"))
	password := to.String(conf.Get("database", "password"))
	name := to.String(conf.Get("database", "name"))

	// Open mysql connection
	db, err = sql.Open("mysql", username+":"+password+"@/"+name)
	if err != nil {
		log.Fatal(err)
	}

	// Sets the maximum number of connections in the idle connection pool
	db.SetMaxIdleConns(100)
}
开发者ID:jonahgeorge,项目名称:featherlabel.com,代码行数:21,代码来源:init.go

示例12: BuildQuery

// Returns a mgo.Query based on the given terms.
func (self *SourceCollection) BuildQuery(terms ...interface{}) *mgo.Query {

	var sort interface{}

	limit := -1
	offset := -1
	sort = nil

	// Conditions
	query := self.compileQuery(terms)

	itop := len(terms)
	for i := 0; i < itop; i++ {
		term := terms[i]

		switch term.(type) {
		case db.Limit:
			limit = int(term.(db.Limit))
		case db.Offset:
			offset = int(term.(db.Offset))
		case db.Sort:
			sort = term.(db.Sort)
		}
	}

	// Actually executing query, returning a pointer.
	q := self.collection.Find(query)

	// Applying limits and offsets.
	if offset > -1 {
		q = q.Skip(offset)
	}

	if limit > -1 {
		q = q.Limit(limit)
	}

	// Sorting result
	if sort != nil {
		for key, val := range sort.(db.Sort) {
			sval := to.String(val)
			if sval == "-1" || sval == "DESC" {
				q = q.Sort("-" + key)
			} else if sval == "1" || sval == "ASC" {
				q = q.Sort(key)
			} else {
				panic(fmt.Sprintf(`Unknown sort value "%s".`, sval))
			}
		}
	}

	return q
}
开发者ID:kdar,项目名称:db,代码行数:54,代码来源:collection.go

示例13: wowhead

func wowhead(options map[string]interface{}) (TMorphItems, error) {
	url := to.String(options["url"])

	// if they just put a wowhead item url in, just output that item
	if matches := wowheadUrlRe.FindStringSubmatch(url); len(matches) > 0 {
		items, err := wowapi([]string{matches[1]})
		if err != nil {
			return nil, errors.New(merry.Details(err))
		}

		if len(items) > 0 {
			return items, nil
		}
	}

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	resp.Body.Close()

	if matches := itemIdRe.FindStringSubmatch(string(data)); len(matches) == 3 {
		//return nil, errors.New(fmt.Sprintf("%#+v", matches))
		count, _ := strconv.Atoi(matches[2])
		if count == 1 {
			items, err := wowapi([]string{matches[1]})
			if err != nil {
				return nil, errors.New(merry.Details(err))
			}

			if len(items) > 0 {
				return items, nil
			}
		} else if count > 1 {
			itemids := strings.Split(matches[1][1:len(matches[1])-1], ":")
			items, err := wowapi(itemids)
			if err != nil {
				return nil, errors.New(merry.Details(err))
			}

			if len(items) > 0 {
				return items, nil
			}
		}
	}

	return nil, errors.New(`Could not find anything to morph on that wowhead page.`)
}
开发者ID:kdar,项目名称:morphgen,代码行数:53,代码来源:wowhead.go

示例14: readConfig

func readConfig(configFileName *string) error {
	file, err := yaml.Open(*configFileName)
	if err != nil {
		return fmt.Errorf("Can't read config file %s: %s", *configFileName, err.Error())
	}
	pidFileName = to.String(file.Get("cache", "pid"))
	logFileName = to.String(file.Get("cache", "log_file"))
	listen = to.String(file.Get("cache", "listen"))
	retentionConfigFileName = to.String(file.Get("cache", "retention-config"))
	redisURI = fmt.Sprintf("%s:%s", to.String(file.Get("redis", "host")), to.String(file.Get("redis", "port")))
	graphiteURI = to.String(file.Get("graphite", "uri"))
	graphitePrefix = to.String(file.Get("graphite", "prefix"))
	graphiteInterval = to.Int64(file.Get("graphite", "interval"))
	return nil
}
开发者ID:warmfusion,项目名称:cache,代码行数:15,代码来源:main.go

示例15: FilterGetAll

func (s Dostow) FilterGetAll(filter map[string]interface{}, count int, skip int, store string, opts gostore.ObjectStoreOptions) (rrows *DostowRows, err error) {
	params := map[string]string{}
	for k, v := range filter {
		params[k] = to.String(v)
	}
	if count > -1 {
		params["size"] = strconv.Itoa(count)
	}
	// resp, bodyBytes, errs := goreq.New().Get(s.url+"/store/"+store).
	// 	SetHeader("X-DOSTOW-GROUP-ACCESS-KEY", s.key).
	// 	Query(filter).
	// 	SetClient(s.client).
	// 	EndBytes()

	resp, err := s.get(s.url+"/store/"+store, params)
	// if resp != nil && resp.Body != nil {
	// 	defer resp.Body.Close()
	// }
	if err != nil {
		logger.Error("Filter GetAll Error:", "err", err)
		return nil, handleError(err)
	}
	defer resp.Body.Close()
	var bodyBytes []byte
	var dst map[string]interface{}
	switch resp.StatusCode {
	case 200:
		bodyBytes, err = getBytes(resp)
		if err != nil {
			return
		}
		if err := json.Unmarshal(bodyBytes, &dst); err != nil {
			return nil, err
		}
		return &DostowRows{dst, bodyBytes}, err
	case 500, 400, 401:
		bodyBytes, err = getBytes(resp)
		if err != nil {
			return
		}
		if err := json.Unmarshal(bodyBytes, &dst); err != nil {
			return nil, newServerError(resp.StatusCode, "Unable to perform action due to server error")
		}
		return nil, newServerError(resp.StatusCode, dst["msg"].(string))
	default:
		return nil, errors.New("Cannot perfrom action")
	}
	return nil, errors.New("Not found")
}
开发者ID:osiloke,项目名称:dostow-contrib,代码行数:49,代码来源:store.go


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