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


Golang strings.Index函数代码示例

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


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

示例1: RenderSpecialLink

func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte {
	ms := MentionPattern.FindAll(rawBytes, -1)
	for _, m := range ms {
		rawBytes = bytes.Replace(rawBytes, m,
			[]byte(fmt.Sprintf(`<a href="/user/%s">%s</a>`, m[1:], m)), -1)
	}
	ms = commitPattern.FindAll(rawBytes, -1)
	for _, m := range ms {
		m = bytes.TrimSpace(m)
		i := strings.Index(string(m), "commit/")
		j := strings.Index(string(m), "#")
		if j == -1 {
			j = len(m)
		}
		rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
			` <code><a href="%s">%s</a></code>`, m, ShortSha(string(m[i+7:j])))), -1)
	}
	ms = issueFullPattern.FindAll(rawBytes, -1)
	for _, m := range ms {
		m = bytes.TrimSpace(m)
		i := strings.Index(string(m), "issues/")
		j := strings.Index(string(m), "#")
		if j == -1 {
			j = len(m)
		}
		rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
			` <a href="%s">#%s</a>`, m, ShortSha(string(m[i+7:j])))), -1)
	}
	ms = issueIndexPattern.FindAll(rawBytes, -1)
	for _, m := range ms {
		rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
			`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)), -1)
	}
	return rawBytes
}
开发者ID:Julianzz,项目名称:gogs,代码行数:35,代码来源:markdown.go

示例2: substituteParams

// substituteParams substitute all params inside double chevron to the correct value
// param value will be obtained from dicts map
func substituteParams(toReplace, words string, dicts map[string]interface{}) string {
	// non empty scalar node remain unchanged
	// except it has double chevron bracket
	if toReplace != "" && (strings.Index(toReplace, "<<") < 0 && strings.Index(toReplace, ">>") < 0) {
		return toReplace
	}
	if words == "" {
		return toReplace
	}

	removeParamBracket := func(param string) string {
		param = strings.TrimSpace(param)
		return param[2 : len(param)-2]
	}

	// search params
	params := dcRe.FindAllString(words, -1)

	// substitute the params
	for _, p := range params {
		pVal := getParamValue(removeParamBracket(p), dicts)
		words = strings.Replace(words, p, pVal, -1)
	}
	return words
}
开发者ID:Jumpscale,项目名称:go-raml,代码行数:27,代码来源:resource.go

示例3: ServeHTTP

func (this *SrcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	tmaster := time.Now()
	switch r.Method { // Likely faster not to use a map[string]func.
	case "GET":
		if strings.Index(r.URL.Path, common.SrcsPath) != 0 {
			handlerutils.HttpError(w, "Bad path: "+r.URL.Path, http.StatusBadRequest)
			return
		}
		this.getHandler(w, r)
	case "POST":
		if strings.Index(r.URL.Path, common.SrcPath) != 0 {
			handlerutils.HttpError(w, "Bad path: "+r.URL.Path, http.StatusBadRequest)
			return
		}
		src := r.URL.Path[len(common.SrcPath):]
		this.postHandler(w, r, src)
	case "PUT":
		if strings.Index(r.URL.Path, common.SrcPath) != 0 {
			handlerutils.HttpError(w, "Bad path: "+r.URL.Path, http.StatusBadRequest)
			return
		}
		src := r.URL.Path[len(common.SrcPath):]
		this.putHandler(w, r, src)
	default:
		handlerutils.HttpError(w, "Bad method: "+r.Method, http.StatusBadRequest)
		return
	}

	glog.V(2).Infof("PERF: total service time: %v\n", time.Now().Sub(tmaster))
}
开发者ID:ceeaspb,项目名称:tsviewdb,代码行数:30,代码来源:srchandler.go

示例4: bzrResolveRepo

func bzrResolveRepo(vcsBzr *vcsCmd, rootDir, remoteRepo string) (realRepo string, err error) {
	outb, err := vcsBzr.runOutput(rootDir, "info "+remoteRepo)
	if err != nil {
		return "", err
	}
	out := string(outb)

	// Expect:
	// ...
	//   (branch root|repository branch): <URL>
	// ...

	found := false
	for _, prefix := range []string{"\n  branch root: ", "\n  repository branch: "} {
		i := strings.Index(out, prefix)
		if i >= 0 {
			out = out[i+len(prefix):]
			found = true
			break
		}
	}
	if !found {
		return "", fmt.Errorf("unable to parse output of bzr info")
	}

	i := strings.Index(out, "\n")
	if i < 0 {
		return "", fmt.Errorf("unable to parse output of bzr info")
	}
	out = out[:i]
	return strings.TrimSpace(string(out)), nil
}
开发者ID:klobucar,项目名称:go,代码行数:32,代码来源:vcs.go

示例5: ReadSNMP

func ReadSNMP(path string) (*Snmp, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	lines := strings.Split(string(data), "\n")

	// Maps a netstat metric to its value (i.e. SyncookiesSent --> 0)
	statMap := make(map[string]string)

	// patterns
	// TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed... <-- header
	// TcpExt: 0 0 1764... <-- values
	for i := 1; i < len(lines); i = i + 2 {
		headers := strings.Fields(lines[i-1][strings.Index(lines[i-1], ":")+1:])
		values := strings.Fields(lines[i][strings.Index(lines[i], ":")+1:])
		for j, header := range headers {
			statMap[header] = values[j]
		}
	}

	out := Snmp{}
	elem := reflect.ValueOf(&out.TCP).Elem()
	typeOfElem := elem.Type()

	for i := 0; i < elem.NumField(); i++ {
		if val, ok := statMap[typeOfElem.Field(i).Name]; ok {
			parsedVal, _ := strconv.ParseUint(val, 10, 64)
			elem.Field(i).SetUint(parsedVal)
		}
	}

	return &out, nil
}
开发者ID:bountylabs,项目名称:goprocinfo,代码行数:35,代码来源:snmp.go

示例6: fileWriter

func fileWriter(t *testing.T, file *os.File, logs []string) {
	filename := file.Name()
	time.Sleep(1 * time.Second) // wait for start Tail...

	for _, line := range logs {
		if strings.Index(line, RotateMarker) != -1 {
			log.Println("fileWriter: rename file => file.old")
			os.Rename(filename, filename+".old")
			file.Close()
			file, _ = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
			log.Println("fileWriter: re-opened file")
		} else if strings.Index(line, TruncateMarker) != -1 {
			time.Sleep(1 * time.Second)
			log.Println("fileWriter: truncate(file, 0)")
			os.Truncate(filename, 0)
			file.Seek(int64(0), os.SEEK_SET)
		}
		_, err := file.WriteString(line)
		log.Print("fileWriter: wrote ", line)
		if err != nil {
			log.Println("write failed", err)
		}
		time.Sleep(1 * time.Millisecond)
	}
	file.Close()
}
开发者ID:cubicdaiya,项目名称:fluent-agent-hydra,代码行数:26,代码来源:in_tail_test.go

示例7: NewSheet

//NewSheet marshal the reader's content, the sst can be nil
//using setSharedStringTable set is later
func NewSheet(r io.Reader, sst *sharedStringTable) (*Sheet, error) {

	data, err := ioutil.ReadAll(r)
	content := string(data)
	index1 := strings.Index(content, `<sheetData>`)
	index2 := strings.Index(content, `</sheetData>`)
	if index1 == -1 {
		return nil, errors.New(fmt.Sprintf("Can't find the sheetData tag, %s", content))
	}
	if index2 == -1 {
		return nil, errors.New(fmt.Sprintf("Can't find the </sheetData> %s", content))
	}
	head := content[0:index1]
	tail := content[index2+len(`</sheetData>`):]
	sheetData := content[index1 : index2+len(`</sheetData>`)]
	if err != nil {
		return nil, err
	}
	sheet := &Sheet{head: head, tail: tail, sst: sst}
	err = xml.Unmarshal([]byte(sheetData), sheet)
	if err != nil {
		return nil, err
	}
	return sheet, nil
}
开发者ID:ZhuBicen,项目名称:xlsx,代码行数:27,代码来源:worksheet.go

示例8: Login

func (h *ZJUJudger) Login(_ UserInterface) error {

	h.client.Get("http://acm.zju.edu.cn/onlinejudge/login.do")

	uv := url.Values{}
	uv.Add("handle", h.username)
	uv.Add("password", h.userpass)

	req, err := http.NewRequest("POST", "http://acm.zju.edu.cn/onlinejudge/login.do", strings.NewReader(uv.Encode()))
	if err != nil {
		return BadInternet
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := h.client.Do(req)
	if err != nil {
		log.Println("err", err)
		return BadInternet
	}
	defer resp.Body.Close()

	b, _ := ioutil.ReadAll(resp.Body)
	html := string(b)

	if strings.Index(html, "Handle or password is invalid.") >= 0 ||
		strings.Index(html, "Handle is required.") >= 0 ||
		strings.Index(html, "Password is required.") >= 0 {
		return LoginFailed
	}

	return nil
}
开发者ID:B88000005,项目名称:vjudger,代码行数:33,代码来源:zoj.go

示例9: cleanGitignore

func cleanGitignore(input string) (output string, err error) {
	if len(input) == 0 {
		return input, nil
	}

	if strings.Contains(input, delimiterStart) {
		if strings.Count(input, delimiterStart) > 1 {
			return input, errors.New("multiple instances of start delimiter")
		}
		if strings.Contains(input, delimiterEnd) {
			if strings.Count(input, delimiterEnd) > 1 {
				return input, errors.New("multiple instances of closing delimiter")
			}
			startPos := strings.Index(input, delimiterStart)
			endPos := strings.Index(input, delimiterEnd) + len(delimiterEnd)

			if startPos-2 >= 0 && input[startPos-2] == '\n' {
				startPos--
			}
			if endPos+1 < len(input) && input[endPos+1] == '\n' {
				endPos++
			}

			output = input[:startPos] + input[endPos:]
		} else {
			return input, errors.New("found no closing delimiter")
		}
	} else {
		output = input
	}

	return output, nil
}
开发者ID:breml,项目名称:gogitignore,代码行数:33,代码来源:cmd.go

示例10: getDirSubdir

// getDirSubdir takes a source and returns a tuple of the URL without
// the subdir and the URL with the subdir.
func getDirSubdir(src string) (string, string) {
	// Calcaulate an offset to avoid accidentally marking the scheme
	// as the dir.
	var offset int
	if idx := strings.Index(src, "://"); idx > -1 {
		offset = idx + 3
	}

	// First see if we even have an explicit subdir
	idx := strings.Index(src[offset:], "//")
	if idx == -1 {
		return src, ""
	}

	idx += offset
	subdir := src[idx+2:]
	src = src[:idx]

	// Next, check if we have query parameters and push them onto the
	// URL.
	if idx = strings.Index(subdir, "?"); idx > -1 {
		query := subdir[idx:]
		subdir = subdir[:idx]
		src += query
	}

	return src, subdir
}
开发者ID:jrperritt,项目名称:terraform,代码行数:30,代码来源:get.go

示例11: filePathsFromArgs

func filePathsFromArgs(args []string) ([]string, error) {
	var output []string
	var err error

	if len(args) == 0 {
		output, err = filepath.Glob("*")
		if err != nil {
			return []string{}, err
		}
	} else {
		for _, arg := range args {
			if strings.Index(arg, "*") < 0 && strings.Index(arg, "?") < 0 {
				output = append(output, arg)
				continue
			}
			matches, err := filepath.Glob(arg)
			if err != nil {
				return []string{}, err
			}
			for _, match := range matches {
				output = append(output, match)
			}
		}
	}

	sort.Strings(output)

	return output, nil
}
开发者ID:vidyacraghav,项目名称:massren,代码行数:29,代码来源:main.go

示例12: TestPurgeOnlyUploads

func TestPurgeOnlyUploads(t *testing.T) {
	oldUploadCount := 5
	oneHourAgo := time.Now().Add(-1 * time.Hour)
	fs := testUploadFS(t, oldUploadCount, "test-repo", oneHourAgo)

	// Create a directory tree outside _uploads and ensure
	// these files aren't deleted.
	dataPath, err := pm.path(uploadDataPathSpec{name: "test-repo", uuid: uuid.New()})
	if err != nil {
		t.Fatalf(err.Error())
	}
	nonUploadPath := strings.Replace(dataPath, "_upload", "_important", -1)
	if strings.Index(nonUploadPath, "_upload") != -1 {
		t.Fatalf("Non-upload path not created correctly")
	}

	nonUploadFile := path.Join(nonUploadPath, "file")
	if err = fs.PutContent(nonUploadFile, []byte("")); err != nil {
		t.Fatalf("Unable to write data file")
	}

	deleted, errs := PurgeUploads(fs, time.Now(), true)
	if len(errs) != 0 {
		t.Error("Unexpected errors", errs)
	}
	for _, file := range deleted {
		if strings.Index(file, "_upload") == -1 {
			t.Errorf("Non-upload file deleted")
		}
	}
}
开发者ID:jhadvig,项目名称:origin,代码行数:31,代码来源:purgeuploads_test.go

示例13: opener

func opener(t *testing.T) func(string) (Reader, Reader) {
	var wrdr, wrdr2 Reader
	return func(path string) (Reader, Reader) {
		buf, _ := ioutil.ReadFile(path)
		rdr := bytes.NewReader(buf)
		rdr2 := bytes.NewReader(buf)
		var err error
		if wrdr == nil {
			wrdr, err = NewReader(rdr)
		} else {
			err = wrdr.Reset(rdr)
		}
		if err != nil {
			if strings.Index(path, "invalid") != -1 {
				return nil, nil
			}
			t.Fatalf("test case: %s; error: %v", path, err)
		}
		if wrdr2 == nil {
			wrdr2, err = NewReader(rdr2)
		} else {
			err = wrdr2.Reset(rdr2)
		}
		if err != nil {
			if strings.Index(path, "invalid") != -1 {
				return nil, nil
			}
			t.Fatalf("test case: %s; error: %v", path, err)
		}
		return wrdr, wrdr2
	}
}
开发者ID:richardlehane,项目名称:webarchive,代码行数:32,代码来源:webarchive_test.go

示例14: testAccDatabaseCheck

func testAccDatabaseCheck(rn string, name *string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[rn]
		if !ok {
			return fmt.Errorf("resource not found: %s", rn)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("database id not set")
		}

		conn := testAccProvider.Meta().(mysqlc.Conn)
		rows, _, err := conn.Query("SHOW CREATE DATABASE terraform_acceptance_test")
		if err != nil {
			return fmt.Errorf("error reading database: %s", err)
		}
		if len(rows) != 1 {
			return fmt.Errorf("expected 1 row reading database but got %d", len(rows))
		}

		row := rows[0]
		createSQL := string(row[1].([]byte))

		if strings.Index(createSQL, "CHARACTER SET utf8") == -1 {
			return fmt.Errorf("database default charset isn't utf8")
		}
		if strings.Index(createSQL, "COLLATE utf8_bin") == -1 {
			return fmt.Errorf("database default collation isn't utf8_bin")
		}

		*name = rs.Primary.ID

		return nil
	}
}
开发者ID:devendraPSL,项目名称:terraform-api,代码行数:35,代码来源:resource_database_test.go

示例15: h_352

// Handle 352 who reply
func (conn *Conn) h_352(line *Line) {
	nk := conn.st.GetNick(line.Args[5])
	if nk == nil {
		logging.Warn("irc.352(): received WHO reply for unknown nick %s",
			line.Args[5])
		return
	}
	if nk == conn.Me() {
		return
	}
	nk.Ident = line.Args[2]
	nk.Host = line.Args[3]
	// XXX: do we care about the actual server the nick is on?
	//      or the hop count to this server?
	// last arg contains "<hop count> <real name>"
	a := strings.SplitN(line.Args[len(line.Args)-1], " ", 2)
	nk.Name = a[1]
	if idx := strings.Index(line.Args[6], "*"); idx != -1 {
		nk.Modes.Oper = true
	}
	if idx := strings.Index(line.Args[6], "B"); idx != -1 {
		nk.Modes.Bot = true
	}
	if idx := strings.Index(line.Args[6], "H"); idx != -1 {
		nk.Modes.Invisible = true
	}
}
开发者ID:Kovensky,项目名称:go-lastfm-bot,代码行数:28,代码来源:state_handlers.go


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