Golang LastIndex示例

说明

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

编程语言: Golang

命名空间/包名称: strings

示例#1
文件: needle.go 项目: xujianhai/gopa

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
}

示例#2
文件: resolve.go 项目: fabxc/govendor

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
}

示例#3
文件: testing.go 项目: gmwu/go

// 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()
}

示例#4
文件: service.go 项目: joyent/gomanta

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
}

示例#5
文件: storage.go 项目: conseweb/goleveldb

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')
}

示例#6
文件: iscsi_util.go 项目: SivagnanamCiena/calico-kubernetes

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
}

示例#7
文件: main.go 项目: vastin/sumatrapdf

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
}

示例#8
文件: builtin_string.go 项目: xyproto/otto

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))
}

示例#9
文件: config.go 项目: ayanamist/MEOW

// 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
}

示例#10
文件: log.go 项目: umisama/golog

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
}

示例#11
文件: lionsmeal.go 项目: luryus/lionsmeal

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)
}

示例#12
文件: service.go 项目: SimiPro/go-cloudinary

// 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))]
}

示例#13

// decorate inserts the final newline if needed and indentation tabs for formatting.
// If addFileLine is true, it also prefixes the string with the file and line of the call site.
func decorate(s string, addFileLine bool) string {
	if addFileLine {
		_, 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
		}
		s = fmt.Sprintf("%s:%d: %s", file, line, s)
	}
	s = "\t" + s // Every line is indented at least one tab.
	n := len(s)
	if n > 0 && s[n-1] != '\n' {
		s += "\n"
		n++
	}
	for i := 0; i < n-1; i++ { // -1 to avoid final newline
		if s[i] == '\n' {
			// Second and subsequent lines are indented an extra tab.
			return s[0:i+1] + "\t" + decorate(s[i+1:n], false)
		}
	}
	return s
}

示例#14
文件: main.go 项目: alexandrev/clean-ttorrent-go

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

}

示例#15
文件: controller_test.go 项目: snormore/flynn

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]")
}

示例#16
文件: data_handle.go 项目: jbenet/data

// 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))
}

示例#17
文件: regexpop.go 项目: NotBadPad/go-learn

func test5() {
	s := `123.125.71.118 - - [11/May/2014:00:00:05 +0800] "GET /company/news/24.html HTTP/1.1" 200 3661 "-" "Mozilla/5.0 (iphone; U; CPU iPhone OS 4_3_5 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5" 120.201.105.162, 127.0.0.1, 10.65.43.62 0.005 0.004`
	//时间
	index := strings.Index(s, "[")
	index1 := strings.Index(s, "]")
	fmt.Println(s[index+1 : index1])

	//uri
	index = strings.Index(s, "\"")
	index1 = strings.Index(s[index+1:], "\"")
	index2 := index + index1 + 1
	temp := s[index+1 : index+index1+1]
	index = strings.Index(temp, " ")
	index1 = strings.Index(temp[index+1:], " ")
	fmt.Println(temp[index+1 : index+index1+1])

	//状态码
	index = strings.Index(s[index2+2:], " ")
	fmt.Println(s[index2+2 : index2+2+index])
	//内容长度
	index = index2 + 2 + index
	index1 = strings.Index(s[index+1:], " ")
	fmt.Println(s[index+1 : index1+1+index])

	//响应时间
	index1 = strings.LastIndex(s, " ")
	fmt.Println(s[index1+1:])
	index = strings.LastIndex(s[:index1], " ")
	fmt.Println(s[index+1 : index1])
}

示例#18
文件: types.go 项目: postfix/appstats

func (r RPCStat) Stack() Stack {
	s := Stack{}

	if r.StackData == "" {
		return s
	}

	lines := strings.Split(r.StackData, "\n")
	for i := 0; i < len(lines); i++ {
		idx := strings.LastIndex(lines[i], " ")
		if idx == -1 {
			break
		}

		cidx := strings.LastIndex(lines[i], ":")
		lineno, _ := strconv.Atoi(lines[i][cidx+1 : idx])
		f := &Frame{
			Location: lines[i][:cidx],
			Lineno:   lineno,
		}

		if i+1 < len(lines) && strings.HasPrefix(lines[i+1], "\t") {
			f.Call = strings.TrimSpace(lines[i+1])
			i++
		}

		s = append(s, f)
	}

	return s[2:]
}

示例#19
文件: service.go 项目: CodeJuan/kubernetes

func validateLeadershipTransition(desired, current string) {
	log.Infof("validating leadership transition")
	// desired, current are of the format <executor-id>:<scheduler-uuid> (see Run()).
	// parse them and ensure that executor ID's match, otherwise the cluster can get into
	// a bad state after scheduler failover: executor ID is a config hash that must remain
	// consistent across failover events.
	var (
		i = strings.LastIndex(desired, ":")
		j = strings.LastIndex(current, ":")
	)

	if i > -1 {
		desired = desired[0:i]
	} else {
		log.Fatalf("desired id %q is invalid", desired)
	}
	if j > -1 {
		current = current[0:j]
	} else if current != "" {
		log.Fatalf("current id %q is invalid", current)
	}

	if desired != current && current != "" {
		log.Fatalf("desired executor id %q != current executor id %q", desired, current)
	}
}

示例#20
文件: export.go 项目: gmmeyer/dbus

// searchHandlers will look through all registered handlers looking for one
// to handle the given path. If a verbatim one isn't found, it will check for
// a subtree registration for the path as well.
func (conn *Conn) searchHandlers(path ObjectPath) (map[string]exportWithMapping, bool) {
	conn.handlersLck.RLock()
	defer conn.handlersLck.RUnlock()

	handlers, ok := conn.handlers[path]
	if ok {
		return handlers, ok
	}

	// If handlers weren't found for this exact path, look for a matching subtree
	// registration
	handlers = make(map[string]exportWithMapping)
	path = path[:strings.LastIndex(string(path), "/")]
	for len(path) > 0 {
		var subtreeHandlers map[string]exportWithMapping
		subtreeHandlers, ok = conn.handlers[path]
		if ok {
			for iface, handler := range subtreeHandlers {
				// Only include this handler if it registered for the subtree
				if handler.includeSubtree {
					handlers[iface] = handler
				}
			}

			break
		}

		path = path[:strings.LastIndex(string(path), "/")]
	}

	return handlers, ok
}

示例#21
文件: 10361.go 项目: codingsince1985/UVa

func main() {
	in, _ := os.Open("10361.in")
	defer in.Close()
	out, _ := os.Create("10361.out")
	defer out.Close()

	s := bufio.NewScanner(in)
	s.Split(bufio.ScanLines)

	var n int
	fmt.Fscanf(in, "%d", &n)
	for n > 0 {
		s.Scan()
		line := s.Text()
		idx21 := strings.Index(line, "<")
		idx22 := strings.Index(line, ">")
		idx41 := strings.LastIndex(line, "<")
		idx42 := strings.LastIndex(line, ">")

		s2 := line[idx21+1 : idx22]
		s3 := line[idx22+1 : idx41]
		s4 := line[idx41+1 : idx42]
		s5 := line[idx42+1:]
		fmt.Fprintln(out, line[:idx21]+s2+s3+s4+s5)

		s.Scan()
		line = s.Text()
		idx := strings.Index(line, "...")
		fmt.Fprintln(out, line[:idx]+s4+s3+s2+s5)
		n--
	}
}

示例#22
文件: main.go 项目: varialus/selenium

func linuxChrome64DriverURL(latest bool) (chrome_driver_url string, driver_version string, err error) {
	chrome_drivers_url := "https://code.google.com/p/chromedriver/downloads/list"
	resp, err := http.Get(chrome_drivers_url)
	if err != nil {
		err = fmt.Errorf("Error: unable to get latest driver from %s", chrome_drivers_url)
		return chrome_driver_url, driver_version, err
	}
	defer resp.Body.Close()
	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		err = fmt.Errorf("Error: unable to read bytes from body while getting driver from %s", chrome_drivers_url)
		return chrome_driver_url, driver_version, err
	}
	chrome_driver_url = string(bytes)
	if latest {
		chrome_driver_url = chrome_driver_url[strings.Index(chrome_driver_url, "'//chromedriver.googlecode.com/files/chromedriver_linux64_"):strings.LastIndex(chrome_driver_url, "supports Chrome")]
		driver_version = chrome_driver_url[strings.LastIndex(chrome_driver_url, "(")+1 : strings.LastIndex(chrome_driver_url, ")")]
		chrome_driver_url = chrome_driver_url[strings.Index(chrome_driver_url, "//"):strings.Index(chrome_driver_url, "',")]
		chrome_driver_url = "https:" + chrome_driver_url
	} else {
		chrome_driver_url = chrome_driver_url[strings.LastIndex(chrome_driver_url, "'//chromedriver.googlecode.com/files/chromedriver_linux64_"):strings.LastIndex(chrome_driver_url, "deprecated")]
		driver_version = "v" + chrome_driver_url[strings.LastIndex(chrome_driver_url, "chromedriver_linux64_")+21:strings.LastIndex(chrome_driver_url, ".zip")]
		chrome_driver_url = chrome_driver_url[strings.Index(chrome_driver_url, "//"):strings.Index(chrome_driver_url, "',")]
		chrome_driver_url = "https:" + chrome_driver_url
	}
	return chrome_driver_url, driver_version, err
}

示例#23
文件: jar.go 项目: alesstimec/persistent-cookiejar

// jarKey returns the key to use for a jar.
func jarKey(host string, psl PublicSuffixList) string {
	if isIP(host) {
		return host
	}

	var i int
	if psl == nil {
		i = strings.LastIndex(host, ".")
		if i == -1 {
			return host
		}
	} else {
		suffix := psl.PublicSuffix(host)
		if suffix == host {
			return host
		}
		i = len(host) - len(suffix)
		if i <= 0 || host[i-1] != '.' {
			// The provided public suffix list psl is broken.
			// Storing cookies under host is a safe stopgap.
			return host
		}
	}
	prevDot := strings.LastIndex(host[:i-1], ".")
	return host[prevDot+1:]
}

示例#24
文件: resolve.go 项目: kouhin/govendor

func (ctx *Context) setPackage(dir, canonical, local, gopath string, status Status) *Package {
	at := 0
	vMiddle := "/" + ctx.VendorDiscoverFolder + "/"
	vStart := 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
		}
	}
	pkg := &Package{
		Dir:       dir,
		Canonical: canonical,
		Local:     local,
		Gopath:    gopath,
		Status:    status,
	}
	ctx.Package[local] = pkg
	return pkg
}

示例#25
文件: xmpp.go 项目: AudioAddict/go-xmpp

// NewClient creates a new connection to a host given as "hostname" or "hostname:port".
// If host is not specified, the  DNS SRV should be used to find the host from the domainpart of the JID.
// Default the port to 5222.
func NewClient(host, user, passwd string, debug bool) (*Client, error) {
	c, err := connect(host, user, passwd)
	if err != nil {
		return nil, err
	}

	tlsconn := tls.Client(c, &DefaultConfig)
	if err = tlsconn.Handshake(); err != nil {
		return nil, err
	}

	if strings.LastIndex(host, ":") > 0 {
		host = host[:strings.LastIndex(host, ":")]
	}
	if err = tlsconn.VerifyHostname(host); err != nil {
		return nil, err
	}

	client := new(Client)
	client.conn = tlsconn
	client.debug = debug

	if err := client.init(user, passwd); err != nil {
		client.Close()
		return nil, err
	}
	return client, nil
}

示例#26
文件: deploy.go 项目: fabric8io/gofabric8

func loadTemplateData(ns string, templateName string, c *k8sclient.Client, oc *oclient.Client) ([]byte, string, error) {
	typeOfMaster := util.TypeOfMaster(c)
	if typeOfMaster == util.Kubernetes {
		catalogName := "catalog-" + templateName
		configMap, err := c.ConfigMaps(ns).Get(catalogName)
		if err != nil {
			return nil, "", err
		}
		for k, v := range configMap.Data {
			if strings.LastIndex(k, ".json") >= 0 {
				return []byte(v), "json", nil
			}
			if strings.LastIndex(k, ".yml") >= 0 || strings.LastIndex(k, ".yaml") >= 0 {
				return []byte(v), "yaml", nil
			}
		}
		return nil, "", fmt.Errorf("Could not find a key for the catalog %s which ends with `.json` or `.yml`", catalogName)

	} else {
		template, err := oc.Templates(ns).Get(templateName)
		if err != nil {
			return nil, "", err
		}
		data, err := json.Marshal(template)
		return data, "json", err
	}
	return nil, "", nil
}

示例#27
文件: utils.go 项目: pathletboy/errors

// name format:
// runtime.goexit
// runtime.main
// main.init
// main.main
// main.init·1 -> main.init
// main.func·001 -> main.func
// github.com/chai2010/errors.New
// ...
func callerInfo(skip int) (name, file string, line int, ok bool) {
	pc, file, line, ok := runtime.Caller(skip)
	if !ok {
		name = "???"
		file = "???"
		line = 1
		return
	}

	name = runtime.FuncForPC(pc).Name()
	if reInit.MatchString(name) {
		name = reInit.ReplaceAllString(name, "init")
	}
	if reClosure.MatchString(name) {
		name = reClosure.ReplaceAllString(name, "func")
	}

	// Truncate file name at last file name separator.
	if idx := strings.LastIndex(file, "/"); idx >= 0 {
		file = file[idx+1:]
	} else if idx = strings.LastIndex(file, "\\"); idx >= 0 {
		file = file[idx+1:]
	}
	return
}

示例#28
文件: bootstrap.go 项目: konce/chaos

func appInfoHandler(w rest.ResponseWriter, r *rest.Request) {
	var marathonApps marathon.MarathonAppsGlobalInfoResponse
	fasthttp.JsonReqAndResHandler(goCore.MarathonAppsUrl, nil, &marathonApps, "GET")
	appsCnt := len(marathonApps.Apps)

	// should not code like this: appsGlobalInfos := [appsCnt]entity.AppsGlobalInfo{}
	appsGlobalInfos := make([]dto.AppsGlobalInfoResponse, appsCnt)

	for i, v := range marathonApps.Apps {
		var perApp dto.AppsGlobalInfoResponse
		if strings.LastIndex(v.Id, "/") == -1 {
			perApp.Id = v.Id
		} else {
			perApp.Id = v.Id[strings.LastIndex(v.Id, "/")+1:]
		}
		perApp.Cpus = strconv.FormatFloat(v.Cpus, 'f', 1, 64)
		perApp.CurrentInstances = strconv.Itoa(v.TasksRunning)
		fmt.Println(v)
		if strings.LastIndex(v.Id, "/") <= 0 { // exclude like /zk or zk
			perApp.Group = "No Groups"
		} else {
			perApp.Group = v.Id[0:strings.LastIndex(v.Id, "/")]
		}
		perApp.Instances = strconv.Itoa(v.Instances)
		perApp.Mem = strconv.FormatFloat(v.Mem, 'f', 1, 64)
		if v.TasksHealthy == 0 && v.TasksUnhealthy == 0 { // when no and healthy check
			perApp.Healthy = "100"
		} else {
			perApp.Healthy = strconv.FormatFloat(float64(v.TasksHealthy)/float64(v.TasksHealthy+v.TasksUnhealthy), 'f', 1, 64)
		}
		perApp.FormatStatus(v.TasksStaged)
		appsGlobalInfos[i] = perApp
	}
	w.WriteJson(appsGlobalInfos)
}

示例#29
文件: common.go 项目: yonglehou/weedfs

func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {
	switch strings.Count(path, "/") {
	case 3:
		parts := strings.Split(path, "/")
		vid, fid, filename = parts[1], parts[2], parts[3]
		ext = filepath.Ext(filename)
	case 2:
		parts := strings.Split(path, "/")
		vid, fid = parts[1], parts[2]
		dotIndex := strings.LastIndex(fid, ".")
		if dotIndex > 0 {
			ext = fid[dotIndex:]
			fid = fid[0:dotIndex]
		}
	default:
		sepIndex := strings.LastIndex(path, "/")
		commaIndex := strings.LastIndex(path[sepIndex:], ",")
		if commaIndex <= 0 {
			vid, isVolumeIdOnly = path[sepIndex+1:], true
			return
		}
		dotIndex := strings.LastIndex(path[sepIndex:], ".")
		vid = path[sepIndex+1 : commaIndex]
		fid = path[commaIndex+1:]
		ext = ""
		if dotIndex > 0 {
			fid = path[commaIndex+1 : dotIndex]
			ext = path[dotIndex:]
		}
	}
	return
}

示例#30
文件: util.go 项目: bombless/cow

// host2Domain returns the domain of a host. It will recognize domains like
// google.com.hk. Returns empty string for simple host.
func host2Domain(host string) (domain string) {
	host, _ = splitHostPort(host)
	if hostIsIP(host) {
		return ""
	}
	host = trimLastDot(host)
	lastDot := strings.LastIndex(host, ".")
	if lastDot == -1 {
		return ""
	}
	// Find the 2nd last dot
	dot2ndLast := strings.LastIndex(host[:lastDot], ".")
	if dot2ndLast == -1 {
		return host
	}

	part := host[dot2ndLast+1 : lastDot]
	// If the 2nd last part of a domain name equals to a top level
	// domain, search for the 3rd part in the host name.
	// So domains like bbc.co.uk will not be recorded as co.uk
	if topLevelDomain[part] {
		dot3rdLast := strings.LastIndex(host[:dot2ndLast], ".")
		if dot3rdLast == -1 {
			return host
		}
		return host[dot3rdLast+1:]
	}
	return host[dot2ndLast+1:]
}

展开阅读全文