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

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

示例1: isNotXIPIOHostErr

func isNotXIPIOHostErr(response []byte) bool {
    if !bytes.Contains(response, []byte("no such host")) {
        return true
    }

    return !bytes.Contains(response, []byte("xip.io"))
}

开发者ID:yacloud-io,项目名称:cf-redis-broker,代码行数:7,代码来源:broker_client.go

示例2: TestTags

// TestTags verifies that the -tags argument controls which files to check.
func TestTags(t *testing.T) {
    // go build
    cmd := exec.Command("go", "build", "-o", binary)
    run(cmd, t)

    // defer removal of vet
    defer os.Remove(binary)

    args := []string{
        "-tags=testtag",
        "-v", // We're going to look at the files it examines.
        "testdata/tagtest",
    }
    cmd = exec.Command("./"+binary, args...)
    output, err := cmd.CombinedOutput()
    if err != nil {
        t.Fatal(err)
    }
    // file1 has testtag and file2 has !testtag.
    if !bytes.Contains(output, []byte(filepath.Join("tagtest", "file1.go"))) {
        t.Error("file1 was excluded, should be included")
    }
    if bytes.Contains(output, []byte(filepath.Join("tagtest", "file2.go"))) {
        t.Error("file2 was included, should be excluded")
    }
}

开发者ID:suifengRock,项目名称:golang-tools,代码行数:27,代码来源:vet_test.go

示例3: oneLevelOfIndentation

// Find one level of whitespace, given indented data
// and a keyword to extract the whitespace in front of
func oneLevelOfIndentation(data *[]byte, keyword string) string {
    whitespace := ""
    kwb := []byte(keyword)
    // If there is a line that contains the given word, extract the whitespace
    if bytes.Contains(*data, kwb) {
        // Find the line that contains they keyword
        var byteline []byte
        found := false
        // Try finding the line with keyword, using \n as the newline
        for _, byteline = range bytes.Split(*data, []byte("\n")) {
            if bytes.Contains(byteline, kwb) {
                found = true
                break
            }
        }
        if found {
            // Find the whitespace in front of the keyword
            whitespaceBytes := byteline[:bytes.Index(byteline, kwb)]
            // Whitespace for one level of indentation
            whitespace = string(whitespaceBytes)
        }
    }
    // Return an empty string, or whitespace for one level of indentation
    return whitespace
}

开发者ID:jeraldrich,项目名称:algernon,代码行数:27,代码来源:utils.go

示例4: slicetest

func slicetest() {
    s := []byte("golang")
    subslice1 := []byte("go")
    subslice2 := []byte("Go")
    fmt.Println(bytes.Contains(s, subslice1))
    fmt.Println(bytes.Contains(s, subslice2))
}

开发者ID:qianguozheng,项目名称:datastructure,代码行数:7,代码来源:parentheses.go

示例5: ram

func ram() interface{} {
    f, err := os.Open("/proc/meminfo")
    if err != nil {
        return "Unsupported"
    }
    defer f.Close()

    bufReader := bufio.NewReader(f)
    b := make([]byte, 0, 100)
    var free, total int

    for line, isPrefix, err := bufReader.ReadLine(); err != io.EOF; line, isPrefix, err = bufReader.ReadLine() {
        if err != nil {
            log.Fatal("bufReader.ReadLine: ", err)
        }
        b = append(b, line...)

        if !isPrefix {
            switch {
            case bytes.Contains(b, []byte("MemFree")):
                free = toInt(bytes.Fields(b)[1])
            case bytes.Contains(b, []byte("MemTotal")):
                total = toInt(bytes.Fields(b)[1])
            }
            b = b[:0]
        }
    }
    return Ram{free, total}
}

开发者ID:amit213,项目名称:simple_status,代码行数:29,代码来源:ram.go

示例6: main

func main() {
    b := []byte("12345678")
    s1 := []byte("456")
    s2 := []byte("789")
    fmt.Println(bytes.Contains(b, s1))
    fmt.Println(bytes.Contains(b, s2))
}

开发者ID:cwen-coder,项目名称:study-gopkg,代码行数:7,代码来源:Contains.go

示例7: NTP

// Test that timesyncd starts using the local NTP server
func NTP(c platform.TestCluster) error {
    m, err := c.NewMachine("")
    if err != nil {
        return fmt.Errorf("Cluster.NewMachine: %s", err)
    }
    defer m.Destroy()

    out, err := m.SSH("networkctl status eth0")
    if err != nil {
        return fmt.Errorf("networkctl: %v", err)
    }
    if !bytes.Contains(out, []byte("NTP: 10.0.0.1")) {
        return fmt.Errorf("Bad network config:\n%s", out)
    }

    plog.Info("Waiting for systemd-timesyncd.service")
    for i := 0; i < 60; i++ {
        out, err = m.SSH("systemctl status systemd-timesyncd.service")
        if err != nil {
            return fmt.Errorf("systemctl: %v", err)
        }

        if bytes.Contains(out, []byte(`Status: "Using Time Server 10.0.0.1:123 (10.0.0.1)."`)) {
            plog.Info("systemd-timesyncd.service is working!")
            return nil
        }

        time.Sleep(time.Second)
    }

    return fmt.Errorf("Bad status:\n%s", out)
}

开发者ID:hanscj1,项目名称:mantle,代码行数:33,代码来源:ntp.go

示例8: TestEditVisitPageMissingPathInfo

func TestEditVisitPageMissingPathInfo(t *testing.T) {
    inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
    if err != nil {
        t.Fatalf("Failed to create instance: %v", err)
    }
    defer inst.Close()

    url := "/editvisit/"
    req, err := inst.NewRequest("GET", url, nil)
    if err != nil {
        t.Fatalf("Failed to create req: %v", err)
    }

    aetest.Login(&user.User{Email: "[email protected]"}, req)

    w := httptest.NewRecorder()
    c := appengine.NewContext(req)

    addTestUser(c, "[email protected]", true)

    editvisitpage(c, w, req)

    code := w.Code
    if code != http.StatusBadRequest {
        t.Errorf("got code %v, want %v", code, http.StatusBadRequest)
    }

    body := w.Body.Bytes()
    expected := []byte("id is missing in path for update request /editvisit/")
    if !bytes.Contains(body, expected) {
        t.Errorf("got body %v, did not contain %v", string(body),
            string(expected))
    }

    url += "12345"
    req, err = inst.NewRequest("GET", url, nil)
    if err != nil {
        t.Fatalf("Failed to create req: %v", err)
    }

    aetest.Login(&user.User{Email: "[email protected]"}, req)

    w = httptest.NewRecorder()
    c = appengine.NewContext(req)

    editvisitpage(c, w, req)

    code = w.Code
    if code != http.StatusBadRequest {
        t.Errorf("got code %v, want %v", code, http.StatusBadRequest)
    }

    body = w.Body.Bytes()
    expected = []byte("id is missing in path for update request /editvisit/")
    if !bytes.Contains(body, expected) {
        t.Errorf("got body %v, did not contain %v", string(body),
            string(expected))
    }

}

开发者ID:jimhopp,项目名称:frederic,代码行数:60,代码来源:web_test.go

示例9: isVolatile

func isVolatile(flagsRequired bool) bool {
    files, err := ioutil.ReadDir(".")
    if err != nil {
        errorExit("fail reading current directory")
    }

    for _, f := range files {
        if f.IsDir() || filepath.Ext(f.Name()) != ".go" {
            continue
        }

        b, err := ioutil.ReadFile(f.Name())
        if err != nil {
            errorExit("fail reading file " + f.Name())
        }

        if bytes.Contains(b, []byte("\nfunc main() {\n")) && bytes.Contains(b, []byte("core.Run()")) {
            if flagsRequired {
                return bytes.Contains(b, []byte("flag.Parse()"))
            }

            return true
        }
    }

    return false
}

开发者ID:volatile,项目名称:volatile,代码行数:27,代码来源:main.go

示例10: TestSetSuperfluousCertTag

func TestSetSuperfluousCertTag(t *testing.T) {
    out := tempFileName()

    const expected = "34cf251b916a54dc9351b832bb0ac7ce"
    cmd := exec.Command(tagBinary, "--out", out, "--set-superfluous-cert-tag", expected, sourceExe)
    if err := cmd.Run(); err != nil {
        t.Fatal(err)
    }

    contents, err := ioutil.ReadFile(out)
    if err != nil {
        t.Fatalf("Failed to read output file: %s", err)
    }
    if !bytes.Contains(contents, []byte(expected)) {
        t.Error("Output doesn't contain expected bytes")
    }

    cmd = exec.Command(tagBinary, "--out", out, "--set-superfluous-cert-tag", expected, "--padded-length", "256", sourceExe)
    if err = cmd.Run(); err != nil {
        t.Fatal(err)
    }

    contents, err = ioutil.ReadFile(out)
    if err != nil {
        t.Fatalf("Failed to read output file: %s", err)
    }
    var zeros [16]byte
    if !bytes.Contains(contents, append([]byte(expected), zeros[:]...)) {
        t.Error("Output doesn't contain expected bytes with padding")
    }
}

开发者ID:0963682490,项目名称:omaha,代码行数:31,代码来源:certificate_tag_test.go

示例11: TestNewWriter_1Sample

func TestNewWriter_1Sample(t *testing.T) {
    t.Parallel()
    is := is.New(t)
    f, err := ioutil.TempFile("", "wavPkgtest")
    is.NoErr(err)
    wr, err := wf.NewWriter(f)
    is.NoErr(err)

    err = wr.WriteSample([]byte{1, 1})
    is.NoErr(err)

    is.Nil(wr.Close())

    f, err = os.Open(f.Name())
    is.NoErr(err)

    b, err := ioutil.ReadAll(f)
    is.NoErr(err)
    is.Equal(len(b), 46)

    is.True(bytes.Contains(b, riff))
    is.True(bytes.Contains(b, wave))
    is.True(bytes.Contains(b, fmt20))

    is.Nil(os.Remove(f.Name()))
}

开发者ID:rtucker88,项目名称:wav,代码行数:26,代码来源:writer_test.go

示例12: TestQuoteTableNames

func TestQuoteTableNames(t *testing.T) {
    dbmap := initDbMap()
    defer dropAndClose(dbmap)

    quotedTableName := dbmap.Dialect.QuoteField("person_test")

    // Use a buffer to hold the log to check generated queries
    logBuffer := &bytes.Buffer{}
    dbmap.TraceOn("", log.New(logBuffer, "gorptest:", log.Lmicroseconds))

    // Create some rows
    p1 := &Person{0, 0, 0, "bob", "smith", 0}
    errorTemplate := "Expected quoted table name %v in query but didn't find it"

    // Check if Insert quotes the table name
    id := dbmap.Insert(p1)
    if !bytes.Contains(logBuffer.Bytes(), []byte(quotedTableName)) {
        t.Errorf(errorTemplate, quotedTableName)
    }
    logBuffer.Reset()

    // Check if Get quotes the table name
    dbmap.Get(Person{}, id)
    if !bytes.Contains(logBuffer.Bytes(), []byte(quotedTableName)) {
        t.Errorf(errorTemplate, quotedTableName)
    }
    logBuffer.Reset()
}

开发者ID:purohit,项目名称:gorp,代码行数:28,代码来源:gorp_test.go

示例13: TestDataCopySubscriptionsForUserAsJSON

func TestDataCopySubscriptionsForUserAsJSON(t *testing.T) {
    pool := newConnPool(t)

    userID, err := data.CreateUser(pool, newUser())
    if err != nil {
        t.Fatal(err)
    }

    buffer := &bytes.Buffer{}
    err = data.CopySubscriptionsForUserAsJSON(pool, buffer, userID)
    if err != nil {
        t.Fatalf("Failed when no subscriptions: %v", err)
    }

    err = data.InsertSubscription(pool, userID, "http://foo")
    if err != nil {
        t.Fatal(err)
    }

    buffer.Reset()
    err = data.CopySubscriptionsForUserAsJSON(pool, buffer, userID)
    if err != nil {
        t.Fatal(err)
    }
    if bytes.Contains(buffer.Bytes(), []byte("foo")) != true {
        t.Errorf("Expected %v, got %v", true, bytes.Contains(buffer.Bytes(), []byte("foo")))
    }
}

开发者ID:jackc,项目名称:tpr,代码行数:28,代码来源:data_test.go

示例14: switchTData

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

    lg, lge := loghttp.Logger(w, r)
    _ = lge

    b := fetch.TestData["test.economist.com"]
    sub1 := []byte(`<li><a href="/sections/newcontinent">xxx</a></li>`)

    sub2 := []byte(`<li><a href="/sections/asia">Asia</a></li>`)
    sub3 := []byte(`<li><a href="/sections/asia">Asia</a></li>
        <li><a href="/sections/newcontinent">xxx</a></li>`)

    if bytes.Contains(b, sub1) {
        b = bytes.Replace(b, sub1, []byte{}, -1)
    } else {
        b = bytes.Replace(b, sub2, sub3, -1)
    }

    if bytes.Contains(b, sub1) {
        lg("now contains %s", sub1)
    } else {
        lg("NOT contains %s", sub1)
    }

    fetch.TestData["test.economist.com"] = b

}

开发者ID:aarzilli,项目名称:tools,代码行数:27,代码来源:6_dir_digest_1.go

示例15: escapeControlCharsFromPayload

// escapeControlCharsFromPayload escapes control chars (\n, \t) from a byte slice.
// Context:
// JSON strings are not supposed to contain control characters such as \n, \t,
// ... but some incoming webhooks might still send invalid JSON and we want to
// try to handle that. An example invalid JSON string from an incoming webhook
// might look like this (strings for both "text" and "fallback" attributes are
// invalid JSON strings because they contain unescaped newlines and tabs):
//  `{
//    "text": "this is a test
//                       that contains a newline and tabs",
//    "attachments": [
//      {
//        "fallback": "Required plain-text summary of the attachment
//                                      that contains a newline and tabs",
//        "color": "#36a64f",
//              ...
//        "text": "Optional text that appears within the attachment
//                               that contains a newline and tabs",
//              ...
//        "thumb_url": "http://example.com/path/to/thumb.png"
//      }
//    ]
//  }`
// This function will search for `"key": "value"` pairs, and escape \n, \t
// from the value.
func escapeControlCharsFromPayload(by []byte) []byte {
    // we'll search for `"text": "..."` or `"fallback": "..."`, ...
    keys := "text|fallback|pretext|author_name|title|value"

    // the regexp reads like this:
    // (?s): this flag let . match \n (default is false)
    // "(keys)": we search for the keys defined above
    // \s*:\s*: followed by 0..n spaces/tabs, a colon then 0..n spaces/tabs
    // ": a double-quote
    // (\\"|[^"])*: any number of times the `\"` string or any char but a double-quote
    // ": a double-quote
    r := `(?s)"(` + keys + `)"\s*:\s*"(\\"|[^"])*"`
    re := regexp.MustCompile(r)

    // the function that will escape \n and \t on the regexp matches
    repl := func(b []byte) []byte {
        if bytes.Contains(b, []byte("\n")) {
            b = bytes.Replace(b, []byte("\n"), []byte("\\n"), -1)
        }
        if bytes.Contains(b, []byte("\t")) {
            b = bytes.Replace(b, []byte("\t"), []byte("\\t"), -1)
        }

        return b
    }

    return re.ReplaceAllFunc(by, repl)
}

开发者ID:ReinhardHsu,项目名称:platform,代码行数:53,代码来源:incoming_webhook.go

示例16: Records

// Records uses Jaro-Winkler distance to parse WHOIS queries.
// Other than .com domains may not be supported.
func Records(data []byte) record {
    lines := bytes.Split(data, []byte("\n"))
    query := make(map[string]string)
    var record record
    for _, line := range lines {
        if jwd.Calculate(strings.Split(string(line), ":")[0], "Referral") > 0.7 && bytes.Contains(line, []byte(":")) {
            record.Referral = strings.TrimSpace(strings.Split(string(line), ": ")[1])
        }
        if len(line) > 0 && bytes.Contains(line, []byte(":")) && len(bytes.TrimSpace(bytes.Split(line, []byte(":"))[1])) > 0 {
            this := string(line)
            if len(query[strings.TrimSpace(strings.Split(this, ":")[0])]) != 0 {
                n := query[strings.TrimSpace(strings.Split(this, ":")[0])]
                query[strings.TrimSpace(strings.Split(this, ":")[0])] = n + "," + strings.TrimSpace(strings.Split(this, ":")[1])
            } else {
                query[strings.TrimSpace(strings.Split(this, ":")[0])] = strings.TrimSpace(strings.Split(this, ":")[1])
            }
        }
    }
    record.Updated = find(query, "Updated")
    record.Created = find(query, "Created")
    record.Nameservers = strings.Split(find(query, "Nameservers"), ",")
    record.Status = strings.Split(find(query, "Status"), ",")
    record.Expiration = find(query, "Expiration")
    return record
}

开发者ID:9uuso,项目名称:whogo,代码行数:27,代码来源:whois.go

示例17: TestCommonKindsRegistered

// TestCommonKindsRegistered verifies that all group/versions registered with
// the testapi package have the common kinds.
func TestCommonKindsRegistered(t *testing.T) {
    for _, kind := range commonKinds {
        for _, group := range testapi.Groups {
            gv := group.GroupVersion()
            gvk := gv.WithKind(kind)
            obj, err := api.Scheme.New(gvk)
            if err != nil {
                t.Error(err)
            }
            defaults := gv.WithKind("")
            if _, got, err := api.Codecs.LegacyCodec().Decode([]byte(`{"kind":"`+kind+`"}`), &defaults, nil); err != nil || gvk != *got {
                t.Errorf("expected %v: %v %v", gvk, got, err)
            }
            data, err := runtime.Encode(api.Codecs.LegacyCodec(*gv), obj)
            if err != nil {
                t.Errorf("expected %v: %v\n%s", gvk, err, string(data))
                continue
            }
            if !bytes.Contains(data, []byte(`"kind":"`+kind+`","apiVersion":"`+gv.String()+`"`)) {
                if kind != "Status" {
                    t.Errorf("expected %v: %v\n%s", gvk, err, string(data))
                    continue
                }
                // TODO: this is wrong, but legacy clients expect it
                if !bytes.Contains(data, []byte(`"kind":"`+kind+`","apiVersion":"v1"`)) {
                    t.Errorf("expected %v: %v\n%s", gvk, err, string(data))
                    continue
                }
            }
        }
    }
}

开发者ID:kubernetes,项目名称:kubernetes,代码行数:34,代码来源:serialization_test.go

示例18: TestHomePage

func TestHomePage(t *testing.T) {
    inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
    if err != nil {
        t.Fatalf("Failed to create instance: %v", err)
    }
    defer inst.Close()

    req, err := inst.NewRequest("GET", "/", nil)
    if err != nil {
        t.Fatalf("Failed to create req1: %v", err)
    }

    aetest.Login(&user.User{Email: "[email protected]"}, req)

    w := httptest.NewRecorder()
    c := appengine.NewContext(req)
    addTestUser(c, "[email protected]", true)

    homepage(c, w, req)

    code := w.Code
    if code != http.StatusOK {
        t.Errorf("got code %v, want %v", code, http.StatusOK)
    }

    body := w.Body.Bytes()
    expected := []byte("[email protected]")
    if !bytes.Contains(body, expected) {
        t.Errorf("got body %v, did not contain %v", string(body), string(expected))
    }
    if !bytes.Contains(body, []byte("Logout")) {
        t.Errorf("got body %v, did not contain %v", body,
            []byte("Logout"))
    }
}

开发者ID:jimhopp,项目名称:frederic,代码行数:35,代码来源:web_test.go

示例19: TestTags

// TestTags verifies that the -tags argument controls which files to check.
func TestTags(t *testing.T) {
    t.Parallel()
    Build(t)
    for _, tag := range []string{"testtag", "x testtag y", "x,testtag,y"} {
        tag := tag
        t.Run(tag, func(t *testing.T) {
            t.Parallel()
            t.Logf("-tags=%s", tag)
            args := []string{
                "-tags=" + tag,
                "-v", // We're going to look at the files it examines.
                "testdata/tagtest",
            }
            cmd := exec.Command("./"+binary, args...)
            output, err := cmd.CombinedOutput()
            if err != nil {
                t.Fatal(err)
            }
            // file1 has testtag and file2 has !testtag.
            if !bytes.Contains(output, []byte(filepath.Join("tagtest", "file1.go"))) {
                t.Error("file1 was excluded, should be included")
            }
            if bytes.Contains(output, []byte(filepath.Join("tagtest", "file2.go"))) {
                t.Error("file2 was included, should be excluded")
            }
        })
    }
}

开发者ID:Harvey-OS,项目名称:go,代码行数:29,代码来源:vet_test.go

示例20: computeInsertedDeletedLines

func computeInsertedDeletedLines(oldCodeR, newCodeR io.Reader) (id InsDel, err error) {
    var i, d int
    // TODO(flowlo): get rid of ReadAll
    var oldCode, newCode []byte
    if oldCode, err = ioutil.ReadAll(oldCodeR); err != nil {
        return
    }

    if newCode, err = ioutil.ReadAll(newCodeR); err != nil {
        return
    }
    currentFields := bytes.Split(newCode, []byte("\n"))
    oldFields := bytes.Split(oldCode, []byte("\n"))
    for _, val := range currentFields {
        if !bytes.Contains(oldCode, val) {
            i++
        }
    }
    for _, val := range oldFields {
        if !bytes.Contains(oldCode, val) {
            d++
        }
    }
    return InsDel{i, d}, nil
}

开发者ID:flowlo,项目名称:coduno-api,代码行数:25,代码来源:util.go

最后编辑: kuteng  文档更新时间: 2021-08-23 19:14   作者:kuteng