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


Golang strings.SplitN函数代码示例

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


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

示例1: ParseLineBasedLine

// TODO write more of a proper parser? (probably not worthwhile given that 2822 is the preferred format)
func ParseLineBasedLine(line string, defaults Manifest2822Entry) (*Manifest2822Entry, error) {
	entry := defaults.Clone()

	parts := strings.SplitN(line, ":", 2)
	if len(parts) < 2 {
		return nil, fmt.Errorf("manifest line missing ':': %s", line)
	}
	entry.Tags = []string{strings.TrimSpace(parts[0])}

	parts = strings.SplitN(parts[1], "@", 2)
	if len(parts) < 2 {
		return nil, fmt.Errorf("manifest line missing '@': %s", line)
	}
	entry.GitRepo = strings.TrimSpace(parts[0])

	parts = strings.SplitN(parts[1], " ", 2)
	entry.GitCommit = strings.TrimSpace(parts[0])
	if len(parts) > 1 {
		entry.Directory = strings.TrimSpace(parts[1])
	}

	if entry.GitFetch == DefaultLineBasedFetch && !GitCommitRegex.MatchString(entry.GitCommit) {
		// doesn't look like a commit, must be a tag
		entry.GitFetch = "refs/tags/" + entry.GitCommit
		entry.GitCommit = "FETCH_HEAD"
	}

	return &entry, nil
}
开发者ID:benbc,项目名称:docker-official-images,代码行数:30,代码来源:line-based.go

示例2: versionParts

// Split a version into parts.
// "1.2.3-beta.2" -> []int{1, 2, 3}, []interface{}{"beta", 2}
func versionParts(v string) ([]int, []interface{}) {
	if strings.HasPrefix(v, "v") || strings.HasPrefix(v, "V") {
		// Strip initial 'v' or 'V' prefix if present.
		v = v[1:]
	}
	parts := strings.SplitN(v, "+", 2)
	parts = strings.SplitN(parts[0], "-", 2)
	fields := strings.Split(parts[0], ".")

	release := make([]int, len(fields))
	for i, s := range fields {
		v, _ := strconv.Atoi(s)
		release[i] = v
	}

	var prerelease []interface{}
	if len(parts) > 1 {
		fields = strings.Split(parts[1], ".")
		prerelease = make([]interface{}, len(fields))
		for i, s := range fields {
			v, err := strconv.Atoi(s)
			if err == nil {
				prerelease[i] = v
			} else {
				prerelease[i] = s
			}
		}
	}

	return release, prerelease
}
开发者ID:ericcapricorn,项目名称:syncthing,代码行数:33,代码来源:upgrade_common.go

示例3: ParseRaw

// Extract the username and password from the authorization
// line of an HTTP header. This function will handle the
// parsing and decoding of the line.
func ParseRaw(authLine string) (string, string, error) {
	parts := strings.SplitN(authLine, " ", 2)
	if len(parts) != 2 {
		return "", "", errors.New("Authorization header malformed.")
	}

	method := parts[0]
	if method != "Basic" {
		return "", "", errors.New("Authorization must be basic.")
	}

	payload := parts[1]
	decodedPayload, err := base64.StdEncoding.DecodeString(payload)
	if err != nil {
		return "", "", err
	}

	userPass := strings.SplitN(string(decodedPayload), ":", 2)
	switch len(userPass) {
	case 1:
		return userPass[0], "", nil
	case 2:
		return userPass[0], userPass[1], nil
	}

	return "", "", errors.New("Unable to parse username or password.")
}
开发者ID:Jwpe,项目名称:l2met,代码行数:30,代码来源:auth.go

示例4: ProcessLSKeys

// This creates the elastic filter porition of a query
func ProcessLSKeys(keystring, filter string, filtered *elastic.FilteredQuery) ([]lsKeyMatch, error) {
	var keys []lsKeyMatch
	var filters []elastic.Filter
	for _, section := range strings.Split(keystring, ",") {
		sp := strings.SplitN(section, ":", 2)
		k := lsKeyMatch{Key: sp[0]}
		if len(sp) == 2 {
			k.RawPattern = sp[1]
			var err error
			k.Pattern, err = regexp.Compile(k.RawPattern)
			if err != nil {
				return nil, err
			}
			re := elastic.NewRegexpFilter(k.Key, k.RawPattern)
			filters = append(filters, re)
		}
		keys = append(keys, k)
	}
	if filter != "" {
		for _, section := range strings.Split(filter, ",") {
			sp := strings.SplitN(section, ":", 2)
			if len(sp) != 2 {
				return nil, fmt.Errorf("error parsing filter string")
			}
			re := elastic.NewRegexpFilter(sp[0], sp[1])
			filters = append(filters, re)
		}
	}
	if len(filters) > 0 {
		and := elastic.NewAndFilter(filters...)
		*filtered = filtered.Filter(and)
	}
	return keys, nil
}
开发者ID:reduxdj,项目名称:grafana,代码行数:35,代码来源:logstash.go

示例5: ParseDigestAuthorizationHeader

// ParseDigestAuthorizationHeader parses an Authorization header and returns a DigestAuthorization object
func ParseDigestAuthorizationHeader(header string) (*DigestAuthorization, error) {
	auth := DigestAuthorization{}

	if len(header) == 0 {
		return &auth, errors.New("Cannot parse Authorization header: no header present")
	}

	opts := make(map[string]string)
	parts := strings.SplitN(header, " ", 2)
	opts["type"] = parts[0]
	parts = strings.Split(parts[1], ",")

	for _, part := range parts {
		vals := strings.SplitN(strings.TrimSpace(part), "=", 2)
		key := vals[0]
		val := strings.Replace(vals[1], "\"", "", -1)
		opts[key] = val
	}

	auth = DigestAuthorization{
		opts["type"],
		opts["source"],
		opts["username"],
		opts["nonce"],
		opts["sig"],
	}
	return &auth, nil
}
开发者ID:WebCivics,项目名称:gold,代码行数:29,代码来源:auth.go

示例6: GetKernelVersion

func GetKernelVersion() (*KernelVersionInfo, error) {
	var (
		flavor               string
		kernel, major, minor int
		err                  error
	)

	uts, err := uname()
	if err != nil {
		return nil, err
	}

	release := make([]byte, len(uts.Release))

	i := 0
	for _, c := range uts.Release {
		release[i] = byte(c)
		i++
	}

	// Remove the \x00 from the release for Atoi to parse correctly
	release = release[:bytes.IndexByte(release, 0)]

	tmp := strings.SplitN(string(release), "-", 2)
	tmp2 := strings.SplitN(tmp[0], ".", 3)

	if len(tmp2) > 0 {
		kernel, err = strconv.Atoi(tmp2[0])
		if err != nil {
			return nil, err
		}
	}

	if len(tmp2) > 1 {
		major, err = strconv.Atoi(tmp2[1])
		if err != nil {
			return nil, err
		}
	}

	if len(tmp2) > 2 {
		minor, err = strconv.Atoi(tmp2[2])
		if err != nil {
			return nil, err
		}
	}

	if len(tmp) == 2 {
		flavor = tmp[1]
	} else {
		flavor = ""
	}

	return &KernelVersionInfo{
		Kernel: kernel,
		Major:  major,
		Minor:  minor,
		Flavor: flavor,
	}, nil
}
开发者ID:p07r0457,项目名称:docker,代码行数:60,代码来源:utils.go

示例7: httpAuth

func httpAuth(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, request *http.Request) {
		if len(request.Header["Authorization"]) == 0 {
			log.Trace(fmt.Sprintf("httpAuth(): 'Authorization' Header Required"))
			http.Error(w, "Authorization Required", http.StatusUnauthorized)
			return
		}

		auth := strings.SplitN(request.Header["Authorization"][0], " ", 2)
		if len(auth) != 2 || auth[0] != "Basic" {
			log.Error(fmt.Sprintf("httpAuth(): Unhandled Authorization Type, Expected Basic"))
			http.Error(w, "Unhandled Authorization Type, Expected Basic\n", http.StatusBadRequest)
			return
		}
		payload, err := base64.StdEncoding.DecodeString(auth[1])
		if err != nil {
			log.Error(fmt.Sprintf("httpAuth(): Authorization base64.StdEncoding.DecodeString() Failed"))
			http.Error(w, "Authorization Failed\n", http.StatusUnauthorized)
			return
		}
		nv := strings.SplitN(string(payload), ":", 2)
		if (len(nv) != 2) || !isAuthorized(nv[0], nv[1]) {
			log.Error(fmt.Sprintf("httpAuth(): Authorization Failed: !isAuthorized() nv: %+v", nv))
			http.Error(w, "Authorization Failed\n", http.StatusUnauthorized)
			return
		}
		h(w, request)
	}
}
开发者ID:predix,项目名称:rdpg-boshrelease,代码行数:29,代码来源:api.go

示例8: Mk_link

/*
	Constructor.
	If bond is supplied, it is assumed to be a one element slice containing another
	link from which the allotment obligation is fetched and will be referenced by the
	link rather than creating a new obligation. Binding two links to an obligation
	allows for easy accounting of total usage allocated (both directions) if the link
	isn't full dupliex.
*/
func Mk_link(sw1 *string, sw2 *string, capacity int64, alarm_thresh int, mlag *string, bond ...*Link) (l *Link) {
	var id string

	id = fmt.Sprintf("%s-%s", *sw1, *sw2)

	tokens := strings.SplitN(*sw1, "@", 2) // for [email protected] names we want only the host as the switch name
	sw1 = &tokens[0]

	tokens = strings.SplitN(*sw2, "@", 2)
	sw2 = &tokens[0]

	l = &Link{
		id:    &id,
		sw1:   sw1,
		sw2:   sw2,
		mlag:  mlag,
		Cost:  1, // for now all links are equal
		port1: -2,
		port2: -2,
	}

	if bond == nil || bond[0] == nil {
		l.allotment = Mk_obligation(capacity, alarm_thresh)
	} else {
		l.allotment = bond[0].Get_allotment()
	}

	return
}
开发者ID:robert-eby,项目名称:tegu,代码行数:37,代码来源:link.go

示例9: insert

// Factoid add: 'key := value' or 'key :is value'
func insert(line *base.Line) {
	if !line.Addressed || !util.IsFactoidAddition(line.Args[1]) {
		return
	}

	var key, val string
	if strings.Index(line.Args[1], ":=") != -1 {
		kv := strings.SplitN(line.Args[1], ":=", 2)
		key = ToKey(kv[0], false)
		val = strings.TrimSpace(kv[1])
	} else {
		// we use :is to add val = "key is val"
		kv := strings.SplitN(line.Args[1], ":is", 2)
		key = ToKey(kv[0], false)
		val = strings.Join([]string{strings.TrimSpace(kv[0]),
			"is", strings.TrimSpace(kv[1])}, " ")
	}
	n, c := line.Storable()
	fact := factoids.NewFactoid(key, val, n, c)

	// The "randomwoot" factoid contains random positive phrases for success.
	joy := "Woo"
	if rand := fc.GetPseudoRand("randomwoot"); rand != nil {
		joy = rand.Value
	}

	if err := fc.Insert(fact); err == nil {
		count := fc.GetCount(key)
		bot.ReplyN(line, "%s, I now know %d things about '%s'.", joy, count, key)
	} else {
		bot.ReplyN(line, "Error storing factoid: %s.", err)
	}
}
开发者ID:pzsz,项目名称:sp0rkle,代码行数:34,代码来源:handlers.go

示例10: environ

// environ merges os.Environ and the given "key=value" pairs.
// If a key is in both os.Environ and kv, kv takes precedence.
func environ(kv []string) []string {
	cur := os.Environ()
	new := make([]string, 0, len(cur)+len(kv))

	envs := make(map[string]string, len(cur))
	for _, ev := range cur {
		elem := strings.SplitN(ev, "=", 2)
		if len(elem) != 2 || elem[0] == "" {
			// pass the env var of unusual form untouched.
			// e.g. Windows may have env var names starting with "=".
			new = append(new, ev)
			continue
		}
		if goos == "windows" {
			elem[0] = strings.ToUpper(elem[0])
		}
		envs[elem[0]] = elem[1]
	}
	for _, ev := range kv {
		elem := strings.SplitN(ev, "=", 2)
		if len(elem) != 2 || elem[0] == "" {
			panic(fmt.Sprintf("malformed env var %q from input", ev))
		}
		if goos == "windows" {
			elem[0] = strings.ToUpper(elem[0])
		}
		envs[elem[0]] = elem[1]
	}
	for k, v := range envs {
		new = append(new, k+"="+v)
	}
	return new
}
开发者ID:pankona,项目名称:mobile,代码行数:35,代码来源:env.go

示例11: decode

// decode decodes a mutation into an equivalent doozer.Event,
// from ../../store/store.go:/decode.
func decode(mut string) (ev doozer.Event, err error) {
	cm := strings.SplitN(mut, ":", 2)

	if len(cm) != 2 {
		err = ErrBadMutation
		return
	}

	ev.Rev, err = strconv.ParseInt(cm[0], 10, 64)
	if err != nil {
		return
	}

	kv := strings.SplitN(cm[1], "=", 2)

	ev.Path = kv[0]
	switch len(kv) {
	case 1:
		ev.Flag = del
	case 2:
		ev.Body = []byte(kv[1])
		ev.Flag = set
	}
	return
}
开发者ID:musicglue,项目名称:doozerd,代码行数:27,代码来源:restore.go

示例12: FilterNamespaces

func (r *templateRouter) FilterNamespaces(namespaces sets.String) {
	r.lock.Lock()
	defer r.lock.Unlock()

	if len(namespaces) == 0 {
		r.state = make(map[string]ServiceAliasConfig)
		r.serviceUnits = make(map[string]ServiceUnit)
	}
	for k := range r.serviceUnits {
		// TODO: the id of a service unit should be defined inside this class, not passed in from the outside
		//   remove the leak of the abstraction when we refactor this code
		ns := strings.SplitN(k, "/", 2)[0]
		if namespaces.Has(ns) {
			continue
		}
		delete(r.serviceUnits, k)
	}

	for k := range r.state {
		ns := strings.SplitN(k, "_", 2)[0]
		if namespaces.Has(ns) {
			continue
		}
		delete(r.state, k)
	}
}
开发者ID:ncdc,项目名称:origin,代码行数:26,代码来源:router.go

示例13: url2BucketAndObject

// url2BucketAndObject gives bucketName and objectName from URL path
func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
	path := c.hostURL.Path
	// Convert any virtual host styled requests
	//
	// For the time being this check is introduced for S3,
	// if you have custom virtual styled hosts please. list them below
	match, _ := filepath.Match("*.s3*.amazonaws.com", c.hostURL.Host)
	switch {
	case match == true:
		hostSplits := strings.SplitN(c.hostURL.Host, ".", 2)
		path = string(c.hostURL.Separator) + hostSplits[0] + c.hostURL.Path
	}

	splits := strings.SplitN(path, string(c.hostURL.Separator), 3)
	switch len(splits) {
	case 0, 1:
		bucketName = ""
		objectName = ""
	case 2:
		bucketName = splits[1]
		objectName = ""
	case 3:
		bucketName = splits[1]
		objectName = splits[2]
	}
	return bucketName, objectName
}
开发者ID:dudymas,项目名称:mc,代码行数:28,代码来源:s3v2.go

示例14: SplitTypeHostSuffix

// Given a command line string representing a resource, break it into type, host identity, and suffix
func SplitTypeHostSuffix(value string) (res ResourceType, host string, suffix string, err error) {
	if value == "" {
		err = errors.New("The identifier must be specified as <host>/<id> or <id>")
		return
	}

	locatorParts := strings.SplitN(value, "://", 2)
	if len(locatorParts) == 2 {
		res = ResourceType(locatorParts[0])
		value = locatorParts[1]
	}

	sections := strings.SplitN(value, "/", 2)
	if len(sections) == 1 {
		suffix = sections[0]
		return
	}
	if strings.TrimSpace(sections[0]) == "" {
		err = errors.New("You must specify <host>/<id> or <id>")
		return
	}
	host = sections[0]
	suffix = sections[1]
	return
}
开发者ID:rajatchopra,项目名称:geard,代码行数:26,代码来源:locator.go

示例15: basicAuth

func (ff *ForwardFrontend) basicAuth(pass http.HandlerFunc) http.HandlerFunc {

	return func(w http.ResponseWriter, r *http.Request) {

		if ff.routeryConfig.Auth != nil {
			if r.Header["Authorization"] == nil || len(r.Header["Authorization"]) <= 0 {
				w.Header().Add("WWW-Authenticate", "Basic")
				http.Error(w, "", 401)
				return
			}

			auth := strings.SplitN(r.Header["Authorization"][0], " ", 2)

			if len(auth) != 2 || auth[0] != "Basic" {
				http.Error(w, "bad syntax", http.StatusBadRequest)
				return
			}

			payload, _ := base64.StdEncoding.DecodeString(auth[1])
			pair := strings.SplitN(string(payload), ":", 2)

			log.Printf("Auth received for user: %v\n", pair[0])
			if len(pair) != 2 || !authentication.Authenticate(ff.routeryConfig, pair[0], pair[1]) {
				http.Error(w, "authorization failed", http.StatusUnauthorized)
				return
			}
		}

		pass(w, r)
	}
}
开发者ID:rpheuts,项目名称:routery,代码行数:31,代码来源:forwardfrontend.go


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