本文整理汇总了Golang中bytes.Contains函数的典型用法代码示例。如果您正苦于以下问题:Golang Contains函数的具体用法?Golang Contains怎么用?Golang Contains使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Contains函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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"))
}
示例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")
}
}
示例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
}
示例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))
}
示例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}
}
示例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))
}
示例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)
}
示例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))
}
}
示例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
}
示例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")
}
}
示例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()))
}
示例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()
}
示例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")))
}
}
示例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
}
示例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)
}