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


Golang strings.LastIndex函数代码示例

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


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

示例1: NewNeedle

func NewNeedle(r *http.Request) (n *Needle, e error) {

	n = new(Needle)
	form, fe := r.MultipartReader()
	if fe != nil {
		log.Error("MultipartReader [ERROR] %s\n", fe)
		e = fe
		return
	}
	part, _ := form.NextPart()
	//log.Println("uploading file " + part.FileName())
	data, _ := ioutil.ReadAll(part)
	n.Data = data

	commaSep := strings.LastIndex(r.URL.Path, ",")
	dotSep := strings.LastIndex(r.URL.Path, ".")
	fid := r.URL.Path[commaSep+1:]
	if dotSep > 0 {
		fid = r.URL.Path[commaSep+1 : dotSep]
	}

	n.ParsePath(fid)

	return
}
开发者ID:xujianhai,项目名称:gopa,代码行数:25,代码来源:needle.go

示例2: setPackage

func (ctx *Context) setPackage(dir, canonical, local, gopath string, status Status) *Package {
	at := 0
	vMiddle := "/" + pathos.SlashToImportPath(ctx.VendorDiscoverFolder) + "/"
	vStart := pathos.SlashToImportPath(ctx.VendorDiscoverFolder) + "/"
	switch {
	case strings.Contains(canonical, vMiddle):
		at = strings.LastIndex(canonical, vMiddle) + len(vMiddle)
	case strings.HasPrefix(canonical, vStart):
		at = strings.LastIndex(canonical, vStart) + len(vStart)
	}
	if at > 0 {
		canonical = canonical[at:]
		if status == StatusUnknown {
			status = StatusVendor
		}
	}
	if status == StatusUnknown {
		if vp := ctx.VendorFilePackageLocal(local); vp != nil {
			status = StatusVendor
			canonical = vp.Path
		}
	}
	if status == StatusUnknown && strings.HasPrefix(canonical, ctx.RootImportPath) {
		status = StatusLocal
	}
	pkg := &Package{
		Dir:       dir,
		Canonical: canonical,
		Local:     local,
		Gopath:    gopath,
		Status:    status,
	}
	ctx.Package[local] = pkg
	return pkg
}
开发者ID:fabxc,项目名称:govendor,代码行数:35,代码来源:resolve.go

示例3: decorate

// decorate prefixes the string with the file and line of the call site
// and inserts the final newline if needed and indentation tabs for formatting.
func decorate(s string) string {
	_, file, line, ok := runtime.Caller(3) // decorate + log + public function.
	if ok {
		// Truncate file name at last file name separator.
		if index := strings.LastIndex(file, "/"); index >= 0 {
			file = file[index+1:]
		} else if index = strings.LastIndex(file, "\\"); index >= 0 {
			file = file[index+1:]
		}
	} else {
		file = "???"
		line = 1
	}
	buf := new(bytes.Buffer)
	// Every line is indented at least one tab.
	buf.WriteByte('\t')
	fmt.Fprintf(buf, "%s:%d: ", file, line)
	lines := strings.Split(s, "\n")
	if l := len(lines); l > 1 && lines[l-1] == "" {
		lines = lines[:l-1]
	}
	for i, line := range lines {
		if i > 0 {
			// Second and subsequent lines are indented an extra tab.
			buf.WriteString("\n\t\t")
		}
		buf.WriteString(line)
	}
	buf.WriteByte('\n')
	return buf.String()
}
开发者ID:gmwu,项目名称:go,代码行数:33,代码来源:testing.go

示例4: PutDirectory

func (m *Manta) PutDirectory(path string) error {
	if err := m.ProcessFunctionHook(m, path); err != nil {
		return err
	}

	realPath := fmt.Sprintf(storagePrefix, m.ServiceInstance.UserAccount, path)

	// Check if parent dirs exist
	m.mu.Lock()
	defer m.mu.Unlock()
	if strings.Contains(path, separator) {
		ppath := path[:strings.LastIndex(path, separator)]
		parents := getParentDirs(m.ServiceInstance.UserAccount, ppath)
		for _, p := range parents {
			if _, ok := m.objects[p]; !ok {
				return fmt.Errorf("%s was not found", p)
			}
		}
	}

	dir := manta.Entry{
		Name:  path[(strings.LastIndex(path, separator) + 1):],
		Type:  typeDirectory,
		Mtime: time.Now().Format(time.RFC3339),
	}

	m.objects[realPath] = dir

	return nil
}
开发者ID:joyent,项目名称:gomanta,代码行数:30,代码来源:service.go

示例5: log

func (s *Storage) log(skip int, str string) {
	s.lmu.Lock()
	defer s.lmu.Unlock()
	_, file, line, ok := runtime.Caller(skip + 2)
	if ok {
		// Truncate file name at last file name separator.
		if index := strings.LastIndex(file, "/"); index >= 0 {
			file = file[index+1:]
		} else if index = strings.LastIndex(file, "\\"); index >= 0 {
			file = file[index+1:]
		}
	} else {
		file = "???"
		line = 1
	}
	fmt.Fprintf(&s.lb, "%s:%d: ", file, line)
	lines := strings.Split(str, "\n")
	if l := len(lines); l > 1 && lines[l-1] == "" {
		lines = lines[:l-1]
	}
	for i, line := range lines {
		if i > 0 {
			s.lb.WriteString("\n\t")
		}
		s.lb.WriteString(line)
	}
	s.lb.WriteByte('\n')
}
开发者ID:conseweb,项目名称:goleveldb,代码行数:28,代码来源:storage.go

示例6: DetachDisk

func (util *ISCSIUtil) DetachDisk(iscsi iscsiDisk, mntPath string) error {
	device, cnt, err := mount.GetDeviceNameFromMount(iscsi.mounter, mntPath)
	if err != nil {
		glog.Errorf("iscsi detach disk: failed to get device from mnt: %s\nError: %v", mntPath, err)
		return err
	}
	if err = iscsi.mounter.Unmount(mntPath, 0); err != nil {
		glog.Errorf("iscsi detach disk: failed to umount: %s\nError: %v", mntPath, err)
		return err
	}
	cnt--
	// if device is no longer used, see if need to logout the target
	if cnt == 0 {
		// strip -lun- from device path
		ind := strings.LastIndex(device, "-lun-")
		prefix := device[:(ind - 1)]
		refCount, err := getDevicePrefixRefCount(iscsi.mounter, prefix)

		if err == nil && refCount == 0 {
			// this portal/iqn are no longer referenced, log out
			// extract portal and iqn from device path
			ind1 := strings.LastIndex(device, "-iscsi-")
			portal := device[(len("/dev/disk/by-path/ip-")):ind1]
			iqn := device[ind1+len("-iscsi-") : ind]

			glog.Infof("iscsi: log out target %s iqn %s", portal, iqn)
			_, err = iscsi.plugin.execCommand("iscsiadm", []string{"-m", "node", "-p", portal, "-T", iqn, "--logout"})
			if err != nil {
				glog.Errorf("iscsi: failed to detach disk Error: %v", err)
			}
		}
	}
	return nil
}
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:34,代码来源:iscsi_util.go

示例7: parseAnalyzeLine

func parseAnalyzeLine(s string) AnalyzeLine {
	sOrig := s
	// remove " [C:\Users\kjk\src\sumatrapdf\vs2015\Installer.vcxproj]" from the end
	end := strings.LastIndex(s, " [")
	fatalif(end == -1, "invalid line '%s'\n", sOrig)
	s = s[:end]
	parts := strings.SplitN(s, "): ", 2)
	fatalif(len(parts) != 2, "invalid line '%s'\n", sOrig)
	res := AnalyzeLine{
		OrigLine: sOrig,
		Message:  parts[1],
	}
	s = parts[0]
	end = strings.LastIndex(s, "(")
	fatalif(end == -1, "invalid line '%s'\n", sOrig)
	// change
	// c:\users\kjk\src\sumatrapdf\ext\unarr\rar\uncompress-rar.c
	// =>
	// ext\unarr\rar\uncompress-rar.c
	path := s[:end]
	// sometimes the line starts with:
	// 11>c:\users\kjk\src\sumatrapdf\ext\bzip2\bzlib.c(238)
	start := strings.Index(path, ">")
	if start != -1 {
		path = path[start+1:]
	}
	start = currDirLen() + 1
	res.FilePath = path[start:]
	n, err := strconv.Atoi(s[end+1:])
	fataliferr(err)
	res.LineNo = n
	return res
}
开发者ID:vastin,项目名称:sumatrapdf,代码行数:33,代码来源:main.go

示例8: builtinString_lastIndexOf

func builtinString_lastIndexOf(call FunctionCall) Value {
	checkObjectCoercible(call.runtime, call.This)
	value := call.This.string()
	target := call.Argument(0).string()
	if 2 > len(call.ArgumentList) || call.ArgumentList[1].IsUndefined() {
		return toValue_int(strings.LastIndex(value, target))
	}
	length := len(value)
	if length == 0 {
		return toValue_int(strings.LastIndex(value, target))
	}
	start := call.ArgumentList[1].number()
	if start.kind == numberInfinity { // FIXME
		// startNumber is infinity, so start is the end of string (start = length)
		return toValue_int(strings.LastIndex(value, target))
	}
	if 0 > start.int64 {
		start.int64 = 0
	}
	end := int(start.int64) + len(target)
	if end > length {
		end = length
	}
	return toValue_int(strings.LastIndex(value[:end], target))
}
开发者ID:xyproto,项目名称:otto,代码行数:25,代码来源:builtin_string.go

示例9: parseMethodPasswdServer

// Parse method:[email protected]:port
func parseMethodPasswdServer(val string) (method, passwd, server, param string, err error) {
	// Use the right-most @ symbol to seperate method:passwd and server:port.
	idx := strings.LastIndex(val, "@")
	if idx == -1 {
		err = errors.New("requires both encrypt method and password")
		return
	}

	methodPasswd := val[:idx]
	server = val[idx+1:]
	idx = strings.LastIndex(server, "?")
	if idx > -1 {
		param = server[idx+1:]
		server = server[:idx]
	} else {
		param = ""
	}
	if err = checkServerAddr(server); err != nil {
		return
	}

	// Password can have : inside, but I don't recommend this.
	arr := strings.SplitN(methodPasswd, ":", 2)
	if len(arr) != 2 {
		err = errors.New("method and password should be separated by :")
		return
	}
	method = arr[0]
	passwd = arr[1]
	return
}
开发者ID:ayanamist,项目名称:MEOW,代码行数:32,代码来源:config.go

示例10: printer

func (l *logger) printer(str string) {
	pc, file_name, line_num, ok := runtime.Caller(3)
	if !ok {
		return
	}

	func_name := runtime.FuncForPC(pc).Name()
	func_name_s := func_name[strings.LastIndex(func_name, ".")+1:]
	file_name_s := file_name[strings.LastIndex(file_name, "/")+1:]

	d := &LogTemplate{
		Time:          time.Now().Format(l.time_fmt),
		FuncName:      func_name,
		ShortFuncName: func_name_s,
		FileName:      file_name,
		ShortFileName: file_name_s,
		LineNumber:    strconv.Itoa(line_num),
		Goroutine:     strconv.Itoa(runtime.NumGoroutine()),
		Message:       str,
	}

	l.log_tmpl.Execute(l.dst, d)

	return
}
开发者ID:umisama,项目名称:golog,代码行数:25,代码来源:log.go

示例11: parseMenuEndingDate

func parseMenuEndingDate(dateStr string) time.Time {
	// dateStr should be like "dd.mm.-dd.mm.yyyy"

	idx := strings.LastIndex(dateStr, ".")                 // find the last dot in the string
	year, err := strconv.ParseUint(dateStr[idx+1:], 10, 0) // and parse the number after it
	if err != nil {
		log.Fatal("Could not parse year: ", err)
	}

	dateStr = dateStr[:idx]                                 // remove the year from the date string
	idx = strings.LastIndex(dateStr, ".")                   // find last dot again
	month, err := strconv.ParseUint(dateStr[idx+1:], 10, 0) // and parse the number after it == month
	if err != nil {
		log.Fatal("Could not parse month: ", err)
	}

	dateStr = dateStr[:idx]                                        // remove the month from the date string
	day, err := strconv.ParseUint(dateStr[len(dateStr)-2:], 10, 0) // try to parse unsigned number using two last characters
	if err != nil {                                                // if fails, probably has dash for the first character
		day, err = strconv.ParseUint(dateStr[len(dateStr)-1:], 10, 0) // parse unsigned number using only the last character
		if err != nil {
			log.Fatal("Could not parse day: ", err)
		}
	}

	return time.Date(int(year), time.Month(month), int(day), 0, 0, 0, 0, time.UTC)
}
开发者ID:luryus,项目名称:lionsmeal,代码行数:27,代码来源:lionsmeal.go

示例12: cleanAssetName

// cleanAssetName returns an asset name from the parent dirname and
// the file name without extension.
// The combination
//   path=/tmp/css/default.css
//   basePath=/tmp/
//   prependPath=new/
// will return
//   new/css/default
func cleanAssetName(path, basePath, prependPath string) string {
	var name string
	path, basePath, prependPath = strings.TrimSpace(path), strings.TrimSpace(basePath), strings.TrimSpace(prependPath)
	basePath, err := filepath.Abs(basePath)
	if err != nil {
		basePath = ""
	}
	apath, err := filepath.Abs(path)
	if err == nil {
		path = apath
	}
	if basePath == "" {
		idx := strings.LastIndex(path, string(os.PathSeparator))
		if idx != -1 {
			idx = strings.LastIndex(path[:idx], string(os.PathSeparator))
		}
		name = path[idx+1:]
	} else {
		// Directory
		name = strings.Replace(path, basePath, "", 1)
		if name[0] == os.PathSeparator {
			name = name[1:]
		}
	}
	if prependPath != "" {
		if prependPath[0] == os.PathSeparator {
			prependPath = prependPath[1:]
		}
		prependPath = EnsureTrailingSlash(prependPath)
	}
	return prependPath + name[:len(name)-len(filepath.Ext(name))]
}
开发者ID:SimiPro,项目名称:go-cloudinary,代码行数:40,代码来源:service.go

示例13: getBaseURL

func getBaseURL(initialBaseURL string) string {
	baseURL := initialBaseURL
	found := false
	idx := 0
	factor := 1
	initialLastIPFragment := strings.LastIndex(baseURL, ".")
	endLastIPFragment := strings.LastIndex(baseURL, ":")
	baseURLFragment := baseURL[0:initialLastIPFragment]
	lastIPFragment := baseURL[initialLastIPFragment+1 : endLastIPFragment]
	port, _ := strconv.Atoi(lastIPFragment)

	for !found {
		portString := strconv.Itoa(port)
		baseURL = baseURLFragment + "." + portString + ":1080"
		log.Printf("Trying to reach tTorrent at the IP: %s", baseURL)
		_, err := http.Get(baseURL + "/torrents")
		if err == nil {
			found = true
		}
		idx = idx + 1
		port = port + idx*factor
		factor = factor * (-1)
	}
	log.Printf("Final value: %s", baseURL)
	return baseURL

}
开发者ID:alexandrev,项目名称:clean-ttorrent-go,代码行数:27,代码来源:main.go

示例14: TestRecreateKey

func (s *S) TestRecreateKey(c *C) {
	key := &ct.Key{Key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3I4gHed4RioRMoJTFdVYp9S6QhHUtMe2cdQAmaN5lVuAaEe9GmJ/wtD4pd7sCpw9daCVOD/WWKCDunrwiEwMNzZKPFQPRfrGAgpCdweD+mk62n/DuaeKJFcfB4C/iLqUrYQ9q0QNnokchI4Ts/CaWoesJOQsbtxDwxcaOlYA/Yq/nY/RA3aK0ZfZqngrOjNRuvhnNFeCF94w2CwwX9ley+PtL0LSWOK2F9D/VEAoRMY89av6WQEoho3vLH7PIOP4OKdla7ezxP9nU14MN4PSv2yUS15mZ14SkA3EF+xmO0QXYUcUi4v5UxkBpoRYNAh32KMMD70pXPRCmWvZ5pRrH [email protected]"}

	originalKey := s.createTestKey(c, key)
	c.Assert(originalKey.ID, Equals, "0c0432006c63fc965ef6946fb67ab559")
	c.Assert(originalKey.Key, Equals, key.Key[:strings.LastIndex(key.Key, " ")])
	c.Assert(originalKey.Comment, Equals, "[email protected]")

	// Post a duplicate
	res, err := s.Post("/keys", key, &ct.Key{})
	c.Assert(err, IsNil)
	c.Assert(res.StatusCode, Equals, 200)

	// Check there is still only one key
	var list []ct.Key
	res, err = s.Get("/keys", &list)
	c.Assert(err, IsNil)
	c.Assert(res.StatusCode, Equals, 200)
	c.Assert(list, HasLen, 1)

	// Delete the original
	path := "/keys/" + originalKey.ID
	res, err = s.Delete(path)
	c.Assert(err, IsNil)
	c.Assert(res.StatusCode, Equals, 200)

	// Create the same key
	newKey := s.createTestKey(c, key)
	c.Assert(newKey.ID, Equals, "0c0432006c63fc965ef6946fb67ab559")
	c.Assert(newKey.Key, Equals, key.Key[:strings.LastIndex(key.Key, " ")])
	c.Assert(newKey.Comment, Equals, "[email protected]")
}
开发者ID:snormore,项目名称:flynn,代码行数:32,代码来源:controller_test.go

示例15: SetDataset

// order: rsplit @, split /, rsplit .
func (d *Handle) SetDataset(s string) {
	// no / is invalid
	if strings.Index(s, "/") == 0 {
		return
	}

	nam_idx := strings.Index(s, "/")
	if nam_idx < 0 {
		nam_idx = 0
	}

	ver_idx := strings.LastIndex(s, "@")
	if ver_idx < 0 {
		ver_idx = len(s) // no version in handle.
	}

	// this precludes names that have periods... use different delimiter?
	fmt_idx := strings.LastIndex(s[nam_idx+1:ver_idx], ".")
	if fmt_idx < 0 {
		fmt_idx = ver_idx // no format in handle.
	} else {
		fmt_idx += nam_idx + 1
	}

	// parts
	d.Author = slice(s, 0, nam_idx)
	d.Name = slice(s, nam_idx+1, fmt_idx)
	d.Format = slice(s, fmt_idx+1, ver_idx)
	d.Version = slice(s, ver_idx+1, len(s))
}
开发者ID:jbenet,项目名称:data,代码行数:31,代码来源:data_handle.go


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