Golang bytes.Contains类(方法)实例源码

下面列出了Golang bytes.Contains 类(方法)源码代码实例,从而了解它的用法。

作者:yacloud-i    项目:cf-redis-broke   
func isNotXIPIOHostErr(response []byte) bool {
	if !bytes.Contains(response, []byte("no such host")) {
		return true
	}

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

作者:suifengRoc    项目:golang-tool   
// 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")
	}
}

作者:jeraldric    项目:algerno   
// 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
}

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

作者:amit21    项目:simple_statu   
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}
}

作者:cwen-code    项目:study-gopk   
func main() {
	b := []byte("12345678")
	s1 := []byte("456")
	s2 := []byte("789")
	fmt.Println(bytes.Contains(b, s1))
	fmt.Println(bytes.Contains(b, s2))
}

作者:hanscj    项目:mantl   
// 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)
}

作者:jimhop    项目:frederi   
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))
	}

}

作者:volatil    项目:volatil   
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
}

作者:096368249    项目:omah   
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")
	}
}

作者:rtucker8    项目:wa   
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()))
}

作者:purohi    项目:gor   
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()
}

作者:jack    项目:tp   
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")))
	}
}

作者:aarzill    项目:tool   
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

}

作者:ReinhardHs    项目:platfor   
// 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)
}

作者:9uus    项目:whog   
// 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
}

作者:kubernete    项目:kubernete   
// 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
				}
			}
		}
	}
}

作者:jimhop    项目:frederi   
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"))
	}
}

作者:Harvey-O    项目:g   
// 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")
			}
		})
	}
}

作者:flowl    项目:coduno-ap   
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
}


问题


面经


文章

微信
公众号

扫码关注公众号