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


Golang strconv.ParseBool函数代码示例

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


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

示例1: GetProfileSearchOptions

// 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
}
开发者ID:riseofthetigers,项目名称:microcosm,代码行数:36,代码来源:profiles.go

示例2: groupUpdate

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}`
}
开发者ID:ChinaLongGanHu,项目名称:wqs,代码行数:34,代码来源:service.go

示例3: getValidationRules

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
}
开发者ID:peek4y,项目名称:gomod,代码行数:60,代码来源:tags.go

示例4: Open

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
}
开发者ID:jmitchell,项目名称:nomad,代码行数:60,代码来源:docker.go

示例5: Load

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
}
开发者ID:fclairamb,项目名称:drone,代码行数:30,代码来源:gitlab.go

示例6: Load

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
}
开发者ID:Ablu,项目名称:drone,代码行数:29,代码来源:gitlab.go

示例7: Fingerprint

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
}
开发者ID:diptanu,项目名称:nomad,代码行数:34,代码来源:docker.go

示例8: SaveNewContent

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)
}
开发者ID:janiukjf,项目名称:GoAdmin,代码行数:34,代码来源:website.go

示例9: SaveContent

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)
}
开发者ID:janiukjf,项目名称:GoAdmin,代码行数:35,代码来源:website.go

示例10: ConverValue

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)

	}
}
开发者ID:zbzzbd,项目名称:go,代码行数:30,代码来源:type.go

示例11: parseBoolean

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
}
开发者ID:skolu,项目名称:gorb,代码行数:32,代码来源:convert.go

示例12: NewContainerManager

// 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
}
开发者ID:jameinel,项目名称:core,代码行数:35,代码来源:lxc.go

示例13: getProcesses

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, &currentOperationID)

		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
}
开发者ID:cristian-sima,项目名称:Wisply,代码行数:60,代码来源:get.go

示例14: ParseEnv

// 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")
		}
	}
}
开发者ID:nikirill,项目名称:cothority,代码行数:31,代码来源:lvl.go

示例15: GetBool

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
}
开发者ID:ishawge,项目名称:go-sdk,代码行数:26,代码来源:func.go


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