Golang ParseBool示例

说明

golang parsebool示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: strconv

示例#1
文件: profiles.go 项目: riseofthetigers/microcosm

// GetProfileSearchOptions fetches the options in the querystring that are being
// used to filter and search for profiles
func GetProfileSearchOptions(query url.Values) ProfileSearchOptions {

	so := ProfileSearchOptions{}

	if query.Get("top") != "" {
		inTop, err := strconv.ParseBool(query.Get("top"))
		if err == nil {
			so.OrderByCommentCount = inTop
		}
	}

	if query.Get("q") != "" {
		startsWith := strings.TrimLeft(query.Get("q"), "[email protected]")
		if startsWith != "" {
			so.StartsWith = startsWith
		}
	}

	if query.Get("following") != "" {
		inFollowing, err := strconv.ParseBool(query.Get("following"))
		if err == nil {
			so.IsFollowing = inFollowing
		}
	}

	if query.Get("online") != "" {
		inFollowing, err := strconv.ParseBool(query.Get("online"))
		if err == nil {
			so.IsOnline = inFollowing
		}
	}

	return so
}

示例#2
文件: service.go 项目: ChinaLongGanHu/wqs

func (s *Server) groupUpdate(group string, queue string,
	write string, read string, url string, ips string) string {

	config, err := s.queue.GetSingleGroup(group, queue)
	if err != nil {
		log.Debugf("GetSingleGroup err:%s", errors.ErrorStack(err))
		return `{"action":"update","result":false}`
	}
	if write != "" {
		w, err := strconv.ParseBool(write)
		if err == nil {
			config.Write = w
		}
	}
	if read != "" {
		r, err := strconv.ParseBool(read)
		if err == nil {
			config.Read = r
		}
	}
	if url != "" {
		config.Url = url
	}
	if ips != "" {
		config.Ips = strings.Split(ips, ",")
	}

	err = s.queue.UpdateGroup(group, queue, config.Write, config.Read, config.Url, config.Ips)
	if err != nil {
		log.Debugf("groupUpdate failed: %s", errors.ErrorStack(err))
		return `{"action":"update","result":false}`
	}
	return `{"action":"update","result":true}`
}

示例#3
文件: tags.go 项目: peek4y/gomod

func getValidationRules(m reflect.StructField) (map[string]interface{}, error) {
	tags := make(map[string]interface{})

	if tagType := m.Tag.Get(TypeTag); tagType != "" {
		switch tagType {
		case EmailTag:
			tags[EmailTag] = true
		case PhoneIndiaTag:
			tags[PhoneIndiaTag] = true
		}
	}

	if tagVal := m.Tag.Get(EmailTag); tagVal != "" {
		boolVal, err := strconv.ParseBool(tagVal)
		if err != nil {
			panic(err)
		}
		if boolVal {
			tags[EmailTag] = boolVal
		}
	}

	if tagVal := m.Tag.Get(RequiredTag); tagVal != "" {
		boolVal, err := strconv.ParseBool(tagVal)
		if err != nil {
			panic(err)
		}
		if boolVal {
			tags[RequiredTag] = boolVal
		}
	}

	if tagVal := m.Tag.Get(PhoneIndiaTag); tagVal != "" {
		boolVal, err := strconv.ParseBool(tagVal)
		if err != nil {
			panic(err)
		}
		if boolVal {
			tags[PhoneIndiaTag] = boolVal
		}
	}

	if tagVal := m.Tag.Get(MaxLenTag); tagVal != "" {
		maxLen, err := strconv.Atoi(tagVal)

		if err == nil {
			tags[MaxLenTag] = maxLen
		}
	}

	if tagVal := m.Tag.Get(MinLenTag); tagVal != "" {
		minLen, err := strconv.Atoi(tagVal)

		if err == nil {
			tags[MinLenTag] = minLen
		}
	}

	return tags, nil
}

示例#4
文件: docker.go 项目: jmitchell/nomad

func (d *DockerDriver) Open(ctx *ExecContext, handleID string) (DriverHandle, error) {
	cleanupContainer, err := strconv.ParseBool(d.config.ReadDefault("docker.cleanup.container", "true"))
	if err != nil {
		return nil, fmt.Errorf("Unable to parse docker.cleanup.container: %s", err)
	}
	cleanupImage, err := strconv.ParseBool(d.config.ReadDefault("docker.cleanup.image", "true"))
	if err != nil {
		return nil, fmt.Errorf("Unable to parse docker.cleanup.image: %s", err)
	}

	// Split the handle
	pidBytes := []byte(strings.TrimPrefix(handleID, "DOCKER:"))
	pid := &dockerPID{}
	err = json.Unmarshal(pidBytes, pid)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse handle '%s': %v", handleID, err)
	}
	d.logger.Printf("[INFO] driver.docker: re-attaching to docker process: %s", handleID)

	// Initialize docker API client
	dockerEndpoint := d.config.ReadDefault("docker.endpoint", "unix:///var/run/docker.sock")
	client, err := docker.NewClient(dockerEndpoint)
	if err != nil {
		return nil, fmt.Errorf("Failed to connect to docker.endpoint (%s): %s", dockerEndpoint, err)
	}

	// Look for a running container with this ID
	containers, err := client.ListContainers(docker.ListContainersOptions{
		Filters: map[string][]string{
			"id": []string{pid.ContainerID},
		},
	})
	if err != nil {
		return nil, fmt.Errorf("Failed to query for container %s: %v", pid.ContainerID, err)
	}

	found := false
	for _, container := range containers {
		if container.ID == pid.ContainerID {
			found = true
		}
	}
	if !found {
		return nil, fmt.Errorf("Failed to find container %s: %v", pid.ContainerID, err)
	}

	// Return a driver handle
	h := &dockerHandle{
		client:           client,
		cleanupContainer: cleanupContainer,
		cleanupImage:     cleanupImage,
		logger:           d.logger,
		imageID:          pid.ImageID,
		containerID:      pid.ContainerID,
		doneCh:           make(chan struct{}),
		waitCh:           make(chan error, 1),
	}
	go h.run()
	return h, nil
}

示例#5
文件: gitlab.go 项目: fclairamb/drone

func Load(env envconfig.Env) *Gitlab {
	config := env.String("REMOTE_CONFIG", "")

	url_, err := url.Parse(config)
	if err != nil {
		panic(err)
	}
	params := url_.Query()
	url_.RawQuery = ""

	gitlab := Gitlab{}
	gitlab.URL = url_.String()
	gitlab.Client = params.Get("client_id")
	gitlab.Secret = params.Get("client_secret")
	gitlab.AllowedOrgs = params["orgs"]
	gitlab.SkipVerify, _ = strconv.ParseBool(params.Get("skip_verify"))
	gitlab.Open, _ = strconv.ParseBool(params.Get("open"))

	switch params.Get("clone_mode") {
	case "oauth":
		gitlab.CloneMode = "oauth"
	default:
		gitlab.CloneMode = "token"
	}

	// this is a temp workaround
	gitlab.Search, _ = strconv.ParseBool(params.Get("search"))

	return &gitlab
}

示例#6
文件: gitlab.go 项目: Ablu/drone

func Load(config string) *Gitlab {
	url_, err := url.Parse(config)
	if err != nil {
		panic(err)
	}
	params := url_.Query()
	url_.RawQuery = ""

	gitlab := Gitlab{}
	gitlab.URL = url_.String()
	gitlab.Client = params.Get("client_id")
	gitlab.Secret = params.Get("client_secret")
	// gitlab.AllowedOrgs = params["orgs"]
	gitlab.SkipVerify, _ = strconv.ParseBool(params.Get("skip_verify"))
	gitlab.HideArchives, _ = strconv.ParseBool(params.Get("hide_archives"))
	// gitlab.Open, _ = strconv.ParseBool(params.Get("open"))

	// switch params.Get("clone_mode") {
	// case "oauth":
	// 	gitlab.CloneMode = "oauth"
	// default:
	// 	gitlab.CloneMode = "token"
	// }

	// this is a temp workaround
	gitlab.Search, _ = strconv.ParseBool(params.Get("search"))

	return &gitlab
}

示例#7
文件: docker.go 项目: diptanu/nomad

func (d *DockerDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
	// Initialize docker API client
	client, err := d.dockerClient()
	if err != nil {
		d.logger.Printf("[DEBUG] driver.docker: could not connect to docker daemon: %v", err)
		return false, nil
	}

	_, err = strconv.ParseBool(d.config.ReadDefault("docker.cleanup.container", "true"))
	if err != nil {
		return false, fmt.Errorf("Unable to parse docker.cleanup.container: %s", err)
	}
	_, err = strconv.ParseBool(d.config.ReadDefault("docker.cleanup.image", "true"))
	if err != nil {
		return false, fmt.Errorf("Unable to parse docker.cleanup.image: %s", err)
	}

	env, err := client.Version()
	if err != nil {
		d.logger.Printf("[DEBUG] driver.docker: could not read version from daemon: %v", err)
		// Check the "no such file" error if the unix file is missing
		if strings.Contains(err.Error(), "no such file") {
			return false, nil
		}

		// We connected to the daemon but couldn't read the version so something
		// is broken.
		return false, err
	}
	node.Attributes["driver.docker"] = "1"
	node.Attributes["driver.docker.version"] = env.Get("Version")

	return true, nil
}

示例#8
文件: website.go 项目: janiukjf/GoAdmin

func SaveNewContent(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.Atoi(r.FormValue("menuid"))
	reqauth, _ := strconv.ParseBool(r.FormValue("requireAuthentication"))
	publish, _ := strconv.ParseBool(r.FormValue("publish"))
	addtomenu, _ := strconv.ParseBool(r.FormValue("addtomenu"))
	pagecontent := r.FormValue("page_content")
	content := models.Content{
		PageTitle:       r.FormValue("page_title"),
		Keywords:        r.FormValue("keywords"),
		MetaTitle:       r.FormValue("meta_title"),
		MetaDescription: r.FormValue("meta_description"),
		Canonical:       r.FormValue("canonical"),
		RequireAuth:     reqauth,
		Published:       publish,
	}
	revision := models.ContentRevision{
		ContentText: pagecontent,
	}
	err := content.Save(revision)
	if err != nil {
		cjson, _ := json.Marshal(&content)
		session, _ := store.Get(r, "adminstuffs")
		session.AddFlash(string(cjson), "content")
		session.AddFlash(pagecontent, "htmlcontent")
		session.Save(r, w)
		http.Redirect(w, r, "/Website/Content/Add/"+strconv.Itoa(id)+"?error="+url.QueryEscape("Page Title is required"), http.StatusFound)
		return
	}
	if addtomenu && id > 0 {
		menu := models.Menu{ID: id}
		menu.AddContent(content.ID)
	}
	http.Redirect(w, r, "/Website/Menu/"+strconv.Itoa(id), http.StatusFound)
}

示例#9
文件: website.go 项目: janiukjf/GoAdmin

func SaveContent(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	id, _ := strconv.Atoi(params.Get(":id"))
	revid, _ := strconv.Atoi(params.Get(":revid"))

	reqauth, _ := strconv.ParseBool(r.FormValue("requireAuthentication"))
	publish, _ := strconv.ParseBool(r.FormValue("publish"))
	pagecontent := r.FormValue("page_content")
	content := models.Content{
		ID:              id,
		PageTitle:       r.FormValue("page_title"),
		Keywords:        r.FormValue("keywords"),
		MetaTitle:       r.FormValue("meta_title"),
		MetaDescription: r.FormValue("meta_description"),
		Canonical:       r.FormValue("canonical"),
		RequireAuth:     reqauth,
		Published:       publish,
	}
	revision := models.ContentRevision{
		ID:          revid,
		ContentID:   id,
		ContentText: pagecontent,
	}
	err := content.Save(revision)
	if err != nil {
		cjson, _ := json.Marshal(&content)
		session, _ := store.Get(r, "adminstuffs")
		session.AddFlash(string(cjson), "content")
		session.AddFlash(pagecontent, "htmlcontent")
		session.Save(r, w)
		http.Redirect(w, r, "/Website/Content/Add/"+strconv.Itoa(id)+"?error="+url.QueryEscape("Page Title is required"), http.StatusFound)
		return
	}
	http.Redirect(w, r, "/Website/Content/Edit/"+strconv.Itoa(id)+"/"+strconv.Itoa(revid)+"?message="+url.QueryEscape("Content Page Updated Successfully!"), http.StatusFound)
}

示例#10
文件: type.go 项目: zbzzbd/go

func (boolType) ConverValue(src interface{}) (value, error) {

	switch s := src.(type) { //src.(type) 这句话什么意思?其中的type又代表什么意思?
	case bool:
		return s, nil
	case string:
		b, err := strconv.ParseBool(s)
		if err != nil {
			return nil, fmt.Errorf("sql/driver: couldn't convert %q into type bool", s)
		}
		return b, nil
	case []byte:
		b, err := strconv.ParseBool(string(s))
		if err != nil {
			return nil, fmt.Errorf("sql/driver:couldn't vonvert %q into type bool ", s)
		}
		return b, nil
	}

	sv := reflect.ValueOf(src)
	switch sv.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		uv := sv.Int()
		if uv == 1 || uv == 0 {
			return uv == 1, nil
		}
		return nil, fmt.Errorf("sql/driver:couldn't convert %v (%T)", src, src)

	}
}

示例#11
文件: convert.go 项目: skolu/gorb

func parseBoolean(value interface{}) (bVal bool, err error) {
	bVal = false
	err = nil

	switch src := value.(type) {
	case nil:
	case bool:
		bVal = src
	case uint64, int64, int, uint, uint32, int32, uint16, int16, uint8, int8:
		var iVal int64
		iVal, err = parseInt(value)
		if err == nil {
			bVal = iVal != 0
		}
	case string:
		bVal, err = strconv.ParseBool(src)
	case []byte:
		if len(src) == 1 {
			if src[0] == 0x0 {
				bVal = false
			} else {
				bVal = true
			}

		} else {
			bVal, err = strconv.ParseBool(string(src))
		}
	default:
		err = fmt.Errorf("Cannot convert to boolean: %v %T", src, src)
	}
	return
}

示例#12
文件: lxc.go 项目: jameinel/core

// NewContainerManager returns a manager object that can start and stop lxc
// containers. The containers that are created are namespaced by the name
// parameter.
func NewContainerManager(conf container.ManagerConfig) (container.Manager, error) {
	name := conf.PopValue(container.ConfigName)
	if name == "" {
		return nil, fmt.Errorf("name is required")
	}
	logDir := conf.PopValue(container.ConfigLogDir)
	if logDir == "" {
		logDir = agent.DefaultLogDir
	}
	// Explicitly ignore the error result from ParseBool.
	// If it fails to parse, the value is false, and this suits
	// us fine.
	useClone, _ := strconv.ParseBool(conf.PopValue("use-clone"))
	useAUFS, _ := strconv.ParseBool(conf.PopValue("use-aufs"))
	backingFS, err := containerDirFilesystem()
	if err != nil {
		// Especially in tests, or a bot, the lxc dir may not exist
		// causing the test to fail. Since we only really care if the
		// backingFS is 'btrfs' and we treat the rest the same, just
		// call it 'unknown'.
		backingFS = "unknown"
	}
	logger.Tracef("backing filesystem: %q", backingFS)
	conf.WarnAboutUnused()
	return &containerManager{
		name:              name,
		logdir:            logDir,
		createWithClone:   useClone,
		useAUFS:           useAUFS,
		backingFilesystem: backingFS,
	}, nil
}

示例#13
文件: get.go 项目: cristian-sima/Wisply

func getProcesses(processType string) []*Process {
	var (
		list        []*Process
		whereClause string
	)
	// fields
	processFields := "process.id, process.is_suspended, process.result, process.content, process.start, process.end, process.is_running, process.current_operation"

	fieldList := processFields

	if processType != "ALL" {
		whereClause = " WHERE process.type ='" + processType + "' "
	}

	// the query
	sql := "SELECT " + fieldList + " FROM `process` AS process " + whereClause + " ORDER BY process.id DESC"

	rows, err := database.Connection.Query(sql)
	if err != nil {
		fmt.Println("Problem when getting all the processes: ")
		fmt.Println(err)
	}

	var (
		ID, currentOperationID                              int
		start, end                                          int64
		content, isRunningString, isSuspendedString, result string
		operation                                           *Operation
	)

	for rows.Next() {
		rows.Scan(&ID, &isSuspendedString, &result, &content, &start, &end, &isRunningString, ¤tOperationID)

		isRunning, err1 := strconv.ParseBool(isRunningString)
		isSuspended, err2 := strconv.ParseBool(isSuspendedString)

		if err1 != nil || err2 != nil {
			fmt.Println(err1)
			fmt.Println(err2)
		}

		if isRunning {
			operation = NewOperation(currentOperationID)
		}

		list = append(list, &Process{
			currentOperation: operation,
			isSuspended:      isSuspended,
			Action: &Action{
				ID:        ID,
				IsRunning: isRunning,
				Start:     start,
				End:       end,
				Content:   content,
				result:    result,
			},
		})
	}
	return list
}

示例#14
文件: lvl.go 项目: nikirill/cothority

// ParseEnv looks at the following environment-variables:
//   DEBUG_LVL - for the actual debug-lvl - default is 1
//   DEBUG_TIME - whether to show the timestamp - default is false
//   DEBUG_COLOR - whether to color the output - default is true
func ParseEnv() {
	var err error
	dv := os.Getenv("DEBUG_LVL")
	if dv != "" {
		debugVisible, err = strconv.Atoi(dv)
		Lvl3("Setting level to", dv, debugVisible, err)
		if err != nil {
			Error("Couldn't convert", dv, "to debug-level")
		}
	}
	dt := os.Getenv("DEBUG_TIME")
	if dt != "" {
		showTime, err = strconv.ParseBool(dt)
		Lvl3("Setting showTime to", dt, showTime, err)
		if err != nil {
			Error("Couldn't convert", dt, "to boolean")
		}
	}
	dc := os.Getenv("DEBUG_COLOR")
	if dc != "" {
		useColors, err = strconv.ParseBool(dc)
		Lvl3("Setting useColor to", dc, showTime, err)
		if err != nil {
			Error("Couldn't convert", dc, "to boolean")
		}
	}
}

示例#15
文件: func.go 项目: ishawge/go-sdk

func GetBool(v interface{}) bool {

	if v == true {
		return true
	}

	if v == false {
		return true
	}

	switch reply := v.(type) {
	case int, int64, float64:
		return reply != 0
	case string:
		n, _ := strconv.ParseBool(reply)
		return n
	case []byte:
		n, _ := strconv.ParseBool(string(reply))
		return n
	case nil:
		return false
	default:
		return false
	}
	return false
}

示例#16
文件: handler.go 项目: vrosnet/kubernetes

// The user can set any or none of the following arguments in any order
// with any twice defined arguments being assigned the first value.
// If the value type for the argument is wrong the field will be assumed to be
// unassigned
// bools: historical, subcontainers, oom_events, creation_events, deletion_events
// ints: max_events, start_time (unix timestamp), end_time (unix timestamp)
// example r.URL: http://localhost:8080/api/v1.3/events?oom_events=true&historical=true&max_events=10
func getEventRequest(r *http.Request) (*events.Request, bool, error) {
	query := events.NewRequest()
	getHistoricalEvents := false

	urlMap := r.URL.Query()

	if val, ok := urlMap["historical"]; ok {
		newBool, err := strconv.ParseBool(val[0])
		if err == nil {
			getHistoricalEvents = newBool
		}
	}
	if val, ok := urlMap["subcontainers"]; ok {
		newBool, err := strconv.ParseBool(val[0])
		if err == nil {
			query.IncludeSubcontainers = newBool
		}
	}
	if val, ok := urlMap["oom_events"]; ok {
		newBool, err := strconv.ParseBool(val[0])
		if err == nil {
			query.EventType[events.TypeOom] = newBool
		}
	}
	if val, ok := urlMap["creation_events"]; ok {
		newBool, err := strconv.ParseBool(val[0])
		if err == nil {
			query.EventType[events.TypeContainerCreation] = newBool
		}
	}
	if val, ok := urlMap["deletion_events"]; ok {
		newBool, err := strconv.ParseBool(val[0])
		if err == nil {
			query.EventType[events.TypeContainerDeletion] = newBool
		}
	}
	if val, ok := urlMap["max_events"]; ok {
		newInt, err := strconv.Atoi(val[0])
		if err == nil {
			query.MaxEventsReturned = int(newInt)
		}
	}
	if val, ok := urlMap["start_time"]; ok {
		newTime, err := time.Parse(time.RFC3339, val[0])
		if err == nil {
			query.StartTime = newTime
		}
	}
	if val, ok := urlMap["end_time"]; ok {
		newTime, err := time.Parse(time.RFC3339, val[0])
		if err == nil {
			query.EndTime = newTime
		}
	}

	glog.V(2).Infof(
		"%v was returned in api/handler.go:getEventRequest from the url rawQuery %v",
		query, r.URL.RawQuery)
	return query, getHistoricalEvents, nil
}

示例#17
文件: cdr.go 项目: cgrates/cgrates

// Populates the field with id from value; strings are appended to original one
func (cdr *CDR) ParseFieldValue(fieldId, fieldVal, timezone string) error {
	var err error
	switch fieldId {
	case utils.ORDERID:
		if cdr.OrderID, err = strconv.ParseInt(fieldVal, 10, 64); err != nil {
			return err
		}
	case utils.TOR:
		cdr.ToR += fieldVal
	case utils.MEDI_RUNID:
		cdr.RunID += fieldVal
	case utils.ACCID:
		cdr.OriginID += fieldVal
	case utils.REQTYPE:
		cdr.RequestType += fieldVal
	case utils.DIRECTION:
		cdr.Direction += fieldVal
	case utils.TENANT:
		cdr.Tenant += fieldVal
	case utils.CATEGORY:
		cdr.Category += fieldVal
	case utils.ACCOUNT:
		cdr.Account += fieldVal
	case utils.SUBJECT:
		cdr.Subject += fieldVal
	case utils.DESTINATION:
		cdr.Destination += fieldVal
	case utils.RATED_FLD:
		cdr.Rated, _ = strconv.ParseBool(fieldVal)
	case utils.SETUP_TIME:
		if cdr.SetupTime, err = utils.ParseTimeDetectLayout(fieldVal, timezone); err != nil {
			return fmt.Errorf("Cannot parse answer time field with value: %s, err: %s", fieldVal, err.Error())
		}
	case utils.PDD:
		if cdr.PDD, err = utils.ParseDurationWithSecs(fieldVal); err != nil {
			return fmt.Errorf("Cannot parse answer time field with value: %s, err: %s", fieldVal, err.Error())
		}
	case utils.ANSWER_TIME:
		if cdr.AnswerTime, err = utils.ParseTimeDetectLayout(fieldVal, timezone); err != nil {
			return fmt.Errorf("Cannot parse answer time field with value: %s, err: %s", fieldVal, err.Error())
		}
	case utils.USAGE:
		if cdr.Usage, err = utils.ParseDurationWithSecs(fieldVal); err != nil {
			return fmt.Errorf("Cannot parse duration field with value: %s, err: %s", fieldVal, err.Error())
		}
	case utils.SUPPLIER:
		cdr.Supplier += fieldVal
	case utils.DISCONNECT_CAUSE:
		cdr.DisconnectCause += fieldVal
	case utils.COST:
		if cdr.Cost, err = strconv.ParseFloat(fieldVal, 64); err != nil {
			return fmt.Errorf("Cannot parse cost field with value: %s, err: %s", fieldVal, err.Error())
		}
	case utils.PartialField:
		cdr.Partial, _ = strconv.ParseBool(fieldVal)
	default: // Extra fields will not match predefined so they all show up here
		cdr.ExtraFields[fieldId] += fieldVal
	}
	return nil
}

示例#18
文件: types.go 项目: qgymje/go_src_code

func (boolType) ConvertValue(src interface{}) (Value, error) {
	switch s := src.(type) {
	case bool:
		return s, nil
	case string:
		b, err := strconv.ParseBool(s)
		if err != nil {
			return nil, fmt.Errorf("sql/driver: couldn't convert %q into type bool", s)
		}
		return b, nil
	case []byte:
		b, err := strconv.ParseBool(string(s))
		if err != nil {
			return nil, fmt.Errorf("sql/driver: couldn't convert %q into type bool", s)
		}
		return b, nil
	}

	sv := reflect.ValueOf(src)
	switch sv.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		iv := sv.Int()
		if iv == 1 || iv == 0 {
			return iv == 1, nil
		}
		return nil, fmt.Errorf("sql/driver: couldn't convert %d into type bool", iv)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		uv := sv.Uint()
		if uv == 1 || uv == 0 {
			return uv == 1, nil
		}
		return nil, fmt.Errorf("sql/driver: couldn't convert %d into type bool", uv)
	}
	return nil, fmt.Errorf("sql/driver: couldn't convert %d (%T) into type bool", src, src)
}

示例#19
文件: github.go 项目: rkrdo/drone

func Load(env envconfig.Env) *Github {
	config := env.String("REMOTE_CONFIG", "")

	// parse the remote DSN configuration string
	url_, err := url.Parse(config)
	if err != nil {
		log.Fatalln("unable to parse remote dsn. %s", err)
	}
	params := url_.Query()
	url_.Path = ""
	url_.RawQuery = ""

	// create the Githbub remote using parameters from
	// the parsed DSN configuration string.
	github := Github{}
	github.URL = url_.String()
	github.Client = params.Get("client_id")
	github.Secret = params.Get("client_secret")
	github.Orgs = params["orgs"]
	github.PrivateMode, _ = strconv.ParseBool(params.Get("private_mode"))
	github.SkipVerify, _ = strconv.ParseBool(params.Get("skip_verify"))
	github.Open, _ = strconv.ParseBool(params.Get("open"))
	github.GitSSH, _ = strconv.ParseBool(params.Get("ssh"))

	if github.URL == DefaultURL {
		github.API = DefaultAPI
	} else {
		github.API = github.URL + "/api/v3/"
	}

	return &github
}

示例#20
文件: vulcand.go 项目: albertrdixon/romulus

func (v *vulcan) NewFrontend(rsc *kubernetes.Resource) (loadbalancer.Frontend, error) {
	s := engine.HTTPFrontendSettings{}
	if val, ok := rsc.GetAnnotation(loadbalancer.PassHostHeaderKey); ok {
		b, _ := strconv.ParseBool(val)
		s.PassHostHeader = b
	}
	if val, ok := rsc.GetAnnotation(loadbalancer.TrustForwardHeadersKey); ok {
		b, _ := strconv.ParseBool(val)
		s.TrustForwardHeader = b
	}
	if val, ok := rsc.GetAnnotation(loadbalancer.FailoverExpressionKey); ok {
		s.FailoverPredicate = val
	}
	if val, ok := rsc.GetAnnotation(loadbalancer.FrontendSettingsKey); ok {
		if er := json.Unmarshal([]byte(val), &s); er != nil {
			logger.Warnf("Failed to parse settings for frontend %q: %v", rsc.ID, er)
		}
	}

	f, er := engine.NewHTTPFrontend(vroute.NewMux(), rsc.ID(), rsc.ID(), NewRoute(rsc.Route).String(), s)
	if er != nil {
		return nil, er
	}
	return newFrontend(f), nil
}

示例#21
文件: fs_test.go 项目: kdevroede/camlistore

func cammountTest(t *testing.T, fn func(env *mountEnv)) {
	dupLog := io.MultiWriter(os.Stderr, testLog{t})
	log.SetOutput(dupLog)
	defer log.SetOutput(os.Stderr)

	w := test.GetWorld(t)
	mountPoint, err := ioutil.TempDir("", "fs-test-mount")
	if err != nil {
		t.Fatal(err)
	}
	verbose := "false"
	var stderrDest io.Writer = ioutil.Discard
	if v, _ := strconv.ParseBool(os.Getenv("VERBOSE_FUSE")); v {
		verbose = "true"
		stderrDest = testLog{t}
	}
	if v, _ := strconv.ParseBool(os.Getenv("VERBOSE_FUSE_STDERR")); v {
		stderrDest = io.MultiWriter(stderrDest, os.Stderr)
	}

	mount := w.Cmd("cammount", "--debug="+verbose, mountPoint)
	mount.Stderr = stderrDest
	mount.Env = append(mount.Env, "CAMLI_TRACK_FS_STATS=1")

	stdin, err := mount.StdinPipe()
	if err != nil {
		t.Fatal(err)
	}
	if err := mount.Start(); err != nil {
		t.Fatal(err)
	}
	waitc := make(chan error, 1)
	go func() { waitc <- mount.Wait() }()
	defer func() {
		log.Printf("Sending quit")
		stdin.Write([]byte("q\n"))
		select {
		case <-time.After(5 * time.Second):
			log.Printf("timeout waiting for cammount to finish")
			mount.Process.Kill()
			Unmount(mountPoint)
		case err := <-waitc:
			log.Printf("cammount exited: %v", err)
		}
		if !test.WaitFor(not(dirToBeFUSE(mountPoint)), 5*time.Second, 1*time.Second) {
			// It didn't unmount. Try again.
			Unmount(mountPoint)
		}
	}()

	if !test.WaitFor(dirToBeFUSE(mountPoint), 5*time.Second, 100*time.Millisecond) {
		t.Fatalf("error waiting for %s to be mounted", mountPoint)
	}
	fn(&mountEnv{
		t:          t,
		mountPoint: mountPoint,
		process:    mount.Process,
	})

}

示例#22
文件: docker.go 项目: pombredanne/openstorage

func (d *driver) specFromOpts(Opts map[string]string) *api.VolumeSpec {
	var spec api.VolumeSpec
	for k, v := range Opts {
		switch k {
		case api.SpecEphemeral:
			spec.Ephemeral, _ = strconv.ParseBool(v)
		case api.SpecSize:
			spec.Size, _ = strconv.ParseUint(v, 10, 64)
		case api.SpecFilesystem:
			spec.Format = api.Filesystem(v)
		case api.SpecBlockSize:
			blockSize, _ := strconv.ParseInt(v, 10, 64)
			spec.BlockSize = int(blockSize)
		case api.SpecHaLevel:
			haLevel, _ := strconv.ParseInt(v, 10, 64)
			spec.HALevel = int(haLevel)
		case api.SpecCos:
			cos, _ := strconv.ParseInt(v, 10, 64)
			spec.Cos = api.VolumeCos(cos)
		case api.SpecDedupe:
			spec.Dedupe, _ = strconv.ParseBool(v)
		case api.SpecSnapshotInterval:
			snapshotInterval, _ := strconv.ParseInt(v, 10, 64)
			spec.SnapshotInterval = int(snapshotInterval)
		}
	}
	return &spec
}

示例#23
文件: docker.go 项目: jmitchell/nomad

func (d *DockerDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
	// Initialize docker API client
	dockerEndpoint := d.config.ReadDefault("docker.endpoint", "unix:///var/run/docker.sock")
	client, err := docker.NewClient(dockerEndpoint)
	if err != nil {
		return false, nil
	}

	_, err = strconv.ParseBool(d.config.ReadDefault("docker.cleanup.container", "true"))
	if err != nil {
		return false, fmt.Errorf("Unable to parse docker.cleanup.container: %s", err)
	}
	_, err = strconv.ParseBool(d.config.ReadDefault("docker.cleanup.image", "true"))
	if err != nil {
		return false, fmt.Errorf("Unable to parse docker.cleanup.image: %s", err)
	}

	env, err := client.Version()
	if err != nil {
		// Check the "no such file" error if the unix file is missing
		if strings.Contains(err.Error(), "no such file") {
			return false, nil
		}

		// We connected to the daemon but couldn't read the version so something
		// is broken.
		return false, err
	}
	node.Attributes["driver.docker"] = "true"
	node.Attributes["driver.docker.version"] = env.Get("Version")

	return true, nil
}

示例#24
文件: options.go 项目: udhos/tabby

func load_options() {
	reader, file := take_reader_from_file(os.Getenv("HOME") + "/.tabbyoptions")
	defer file.Close()
	var str string
	for next_string_from_reader(reader, &str) {
		args := strings.Split(compact_space(str), "\t")
		switch args[0] {
		case "space_not_tab":
			opt.space_not_tab, _ = strconv.ParseBool(args[1])
		case "show_search":
			opt.show_search, _ = strconv.ParseBool(args[1])
		case "show_error":
			opt.show_error, _ = strconv.ParseBool(args[1])
		case "ihp_position":
			opt.ihp_position = atoi(args[1])
		case "ohp_position":
			opt.ohp_position = atoi(args[1])
		case "vvp_position":
			opt.vvp_position = atoi(args[1])
		case "alloc_window":
			opt.window_width, opt.window_height, opt.window_x, opt.window_y = atoi(args[1]),
				atoi(args[2]), atoi(args[3]), atoi(args[4])
		case "font":
			opt.font = args[1]
		case "tabsize":
			opt.tabsize = atoi(args[1])
		}
	}
}

示例#25
文件: bridge.go 项目: jak-atx/vic

func (c *networkConfiguration) fromLabels(labels map[string]string) error {
	var err error
	for label, value := range labels {
		switch label {
		case BridgeName:
			c.BridgeName = value
		case netlabel.DriverMTU:
			if c.Mtu, err = strconv.Atoi(value); err != nil {
				return parseErr(label, value, err.Error())
			}
		case netlabel.EnableIPv6:
			if c.EnableIPv6, err = strconv.ParseBool(value); err != nil {
				return parseErr(label, value, err.Error())
			}
		case EnableIPMasquerade:
			if c.EnableIPMasquerade, err = strconv.ParseBool(value); err != nil {
				return parseErr(label, value, err.Error())
			}
		case EnableICC:
			if c.EnableICC, err = strconv.ParseBool(value); err != nil {
				return parseErr(label, value, err.Error())
			}
		case DefaultBridge:
			if c.DefaultBridge, err = strconv.ParseBool(value); err != nil {
				return parseErr(label, value, err.Error())
			}
		case DefaultBindingIP:
			if c.DefaultBindingIP = net.ParseIP(value); c.DefaultBindingIP == nil {
				return parseErr(label, value, "nil ip")
			}
		}
	}

	return nil
}

示例#26
文件: snapshots.go 项目: murdinc/awsm

// Marshal puts items from SimpleDB into a Snapshot Class
func (c SnapshotClasses) Marshal(items []*simpledb.Item) {
	for _, item := range items {
		name := strings.Replace(*item.Name, "snapshots/", "", -1)
		cfg := new(SnapshotClass)
		for _, attribute := range item.Attributes {

			val := *attribute.Value

			switch *attribute.Name {

			case "Propagate":
				cfg.Propagate, _ = strconv.ParseBool(val)

			case "PropagateRegions":
				cfg.PropagateRegions = append(cfg.PropagateRegions, val)

			case "Retain":
				cfg.Retain, _ = strconv.Atoi(val)

			case "Rotate":
				cfg.Rotate, _ = strconv.ParseBool(val)

			case "VolumeID":
				cfg.VolumeID = val

			}
		}
		c[name] = *cfg
	}
}

示例#27
文件: list.go 项目: harshalhshah/rack

func (command *commandList) HandleFlags(resource *handler.Resource) error {
	c := command.Ctx.CLIContext
	opts := &osNetworks.ListOpts{
		Name:     c.String("name"),
		TenantID: c.String("tenant-id"),
		Status:   c.String("status"),
		Marker:   c.String("marker"),
		Limit:    c.Int("limit"),
	}
	if c.IsSet("up") {
		upRaw := c.String("up")
		up, err := strconv.ParseBool(upRaw)
		if err != nil {
			return fmt.Errorf("Invalid value for flag `up`: %s. Options are: true, false", upRaw)
		}
		opts.AdminStateUp = &up
	}
	if c.IsSet("shared") {
		sharedRaw := c.String("shared")
		shared, err := strconv.ParseBool(sharedRaw)
		if err != nil {
			return fmt.Errorf("Invalid value for flag `shared`: %s. Options are: true, false", sharedRaw)
		}
		opts.Shared = &shared
	}
	resource.Params = ¶msList{
		opts:     opts,
		allPages: c.Bool("all-pages"),
	}
	return nil
}

示例#28
文件: main_test.go 项目: bbrks/advent-of-code

func TestIsNice(t *testing.T) {
	file, err := os.Open("input_test")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := strings.Split(scanner.Text(), ",")
		ret := isNice(&line[0])
		expect, err := strconv.ParseBool(line[1])
		if err == nil && ret != expect {
			t.Errorf("Test failed, got: '%t', expected: '%t'", ret, expect)
		}
		ret = isNice2(&line[0])
		expect, err = strconv.ParseBool(line[2])
		if err == nil && ret != expect {
			t.Errorf("Test failed, got: '%t', expected: '%t'", ret, expect)
		}
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
}

示例#29
文件: golog.go 项目: itchio/butler

func LoggerFor(prefix string) Logger {

	l := &logger{
		prefix: prefix + ": ",
		pc:     make([]uintptr, 10),
	}

	trace := os.Getenv("TRACE")
	l.traceOn, _ = strconv.ParseBool(trace)
	if !l.traceOn {
		prefixes := strings.Split(trace, ",")
		for _, p := range prefixes {
			if prefix == strings.Trim(p, " ") {
				l.traceOn = true
				break
			}
		}
	}
	if l.traceOn {
		l.traceOut = l.newTraceWriter()
	} else {
		l.traceOut = ioutil.Discard
	}

	printStack := os.Getenv("PRINT_STACK")
	l.printStack, _ = strconv.ParseBool(printStack)

	return l
}

示例#30
文件: pollmsg.go 项目: hinike/gowebQQ

func (this *PollMessage) IsSessMessage() (ret *SessMessage, is bool) {
	if this.retCode != 0 || this.pollType != PT_SessMessage {
		return nil, false
	}
	js, _ := simplejson.NewJson(this.value)
	ret = new(SessMessage)
	ret.MessageId = int64(js.Get("msg_id").MustFloat64())
	ret.MessageId2 = int64(js.Get("msg_id2").MustFloat64())
	ret.ToUin = fmt.Sprint(int64(js.Get("to_uin").MustFloat64()))
	ret.FromUin = fmt.Sprint(int64(js.Get("from_uin").MustFloat64()))
	ret.MessageType = int64(js.Get("msg_type").MustFloat64())
	ret.ReplyIp = int64(js.Get("admin_uin").MustFloat64())
	ret.Time = time.Unix(int64(js.Get("time").MustFloat64()), 0)
	ret.Id = fmt.Sprint(int64(js.Get("id").MustFloat64()))
	ret.Ruin = fmt.Sprint(int64(js.Get("ruin").MustFloat64()))
	ret.ServiceType = int64(js.Get("service_type").MustFloat64())

	ret.Flags.Text, _ = strconv.ParseBool(fmt.Sprint(js.Get("flags").Get("text").MustInt(1)))
	ret.Flags.Audio, _ = strconv.ParseBool(fmt.Sprint(js.Get("flags").Get("audio").MustInt(1)))
	ret.Flags.File, _ = strconv.ParseBool(fmt.Sprint(js.Get("flags").Get("file").MustInt(1)))
	ret.Flags.Pic, _ = strconv.ParseBool(fmt.Sprint(js.Get("flags").Get("pic").MustInt(1)))
	ret.Flags.Video, _ = strconv.ParseBool(fmt.Sprint(js.Get("flags").Get("video").MustInt(1)))

	ret.Font.Size = js.Get("content").GetIndex(0).GetIndex(1).Get("size").MustInt(15)

	ret.Font.Color = js.Get("content").GetIndex(0).GetIndex(1).Get("color").MustString("000000")
	ret.Font.Name = js.Get("content").GetIndex(0).GetIndex(1).Get("name").MustString("宋体")
	for i := 1; i < len(js.Get("content").MustArray([]interface{}{})); i++ {
		ret.Content = append(ret.Content, fmt.Sprint(js.Get("content").GetIndex(i)))
	}
	return
}

展开阅读全文