本文整理汇总了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
}
示例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
}
示例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))
}
示例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
}
示例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
}
示例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()
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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")
}
}
}
示例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
}
}
示例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
}
}
示例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
}
}