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


Golang bytes.TrimPrefix函数代码示例

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


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

示例1: ExampleTrimPrefix

func ExampleTrimPrefix() {
	var b = []byte("Goodbye,, world!")
	b = bytes.TrimPrefix(b, []byte("Goodbye,"))
	b = bytes.TrimPrefix(b, []byte("See ya,"))
	fmt.Printf("Hello%s", b)
	// Output: Hello, world!
}
开发者ID:achanda,项目名称:go,代码行数:7,代码来源:example_test.go

示例2: ReadHeader

// CommitV000
// TreeV000
// XAttrSetV000
func ReadHeader(p *bytes.Buffer) (header *Header, err error) {
	header = &Header{}
	prefix := p.Next(4)
	var version []byte
	if bytes.Equal(prefix, []byte("Comm")) {
		header.Data = append(prefix, p.Next(6)...)
		header.Type = BLOB_TYPE_COMMIT
		version = bytes.TrimPrefix(header.Data, []byte("CommitV"))
	} else if bytes.Equal(prefix, []byte("Tree")) {
		header.Data = append(prefix, p.Next(4)...)
		header.Type = BLOB_TYPE_TREE
		version = bytes.TrimPrefix(header.Data, []byte("TreeV"))
	} else if bytes.Equal(prefix, []byte("XAtt")) {
		header.Data = append(prefix, p.Next(8)...)
		header.Type = BLOB_TYPE_X_ATTR_SET
		version = bytes.TrimPrefix(header.Data, []byte("XAttrSetV"))
	} else {
		err = errors.New(fmt.Sprintf("ReadHeader header %s has unknown type", header.Data))
		return
	}
	if header.Version, err = strconv.Atoi(string(version)); err != nil {
		err = errors.New(fmt.Sprintf("ReadHeader header %s has non-integer version", header.Data))
		return
	}
	return
}
开发者ID:asimihsan,项目名称:arqinator,代码行数:29,代码来源:header.go

示例3: detectLicense

func detectLicense(filepath string) (LicenseType, error) {
	fh, err := os.Open(filepath)
	if err != nil {
		return UNKNOWN, err
	}
	defer fh.Close()

	var buf bytes.Buffer
	scanner := bufio.NewScanner(fh)
	for scanner.Scan() {
		if bytes.HasPrefix(scanner.Bytes(), []byte("package ")) {
			break
		}
		line := bytes.TrimSuffix(bytes.TrimPrefix(bytes.TrimPrefix(scanner.Bytes(),
			[]byte("//")), []byte("/*")), []byte("*/"))
		if len(line) > 0 && (line[0] == '+' || bytes.HasPrefix(bytes.TrimSpace(line), []byte("Copyright"))) {
			continue
		}
		buf.Write(bytes.TrimSpace(line))
		buf.WriteByte('\n')
	}
	//fmt.Fprintf(os.Stderr, "DETECT %q\n", strings.TrimSpace(buf.String()))
	l := license.New("", strings.TrimSpace(buf.String()))
	l.File = filepath
	if err = l.GuessType(); err != nil {
		if err.Error() == license.ErrUnrecognizedLicense {
			return UNKNOWN, scanner.Err()
		}
		return UNKNOWN, err
	}

	err = scanner.Err()
	switch l.Type {
	case license.LicenseMIT:
		return MIT, err
	case license.LicenseNewBSD:
		return NewBSD, err
	case license.LicenseFreeBSD:
		return Freebsd, err
	case license.LicenseApache20:
		return Apache2, err
	case license.LicenseMPL20:
		return MPL2, err
	case license.LicenseGPL20:
		return GPL2, err
	case license.LicenseGPL30:
		return GPL3, err
	case license.LicenseLGPL21:
		return LGPL2, err
	case license.LicenseLGPL30:
		return LGPL2, err
	case license.LicenseCDDL10:
		return CDDL, err
	case license.LicenseEPL10:
		return EPL, err
	}
	return UNKNOWN, err
}
开发者ID:tgulacsi,项目名称:licentia,代码行数:58,代码来源:licentia.go

示例4: DetectCode

func DetectCode(first, second Line, detectors Detectors) Handler {
	if !first.hasFourSpacePrefix() {
		return nil
	}
	block := md.CodeBlock{}
	var paused *Line
	return HandlerFunc(func(next Line, ctx Context) (bool, error) {
		if next.EOF() {
			ctx.Emit(block)
			ctx.Emit(md.End{})
			return maybeNull(paused, ctx)
		}
		// TODO(akavel): verify it's coded ok, it was converted from a different approach
		fourspace := []byte("    ")
		switch {
		// previous was blank, next is not tab-indented. Reject both.
		case paused != nil && !next.hasFourSpacePrefix():
			ctx.Emit(block)
			ctx.Emit(md.End{})
			return maybeNull(paused, ctx)
		case next.isBlank():
			if paused != nil {
				block.Raw = append(block.Raw, md.Run(*paused))
				block.Prose = append(block.Prose, md.Run{
					paused.Line, bytes.TrimPrefix(paused.Bytes, fourspace)})
			}
			paused = &next // note: only case where we pause a line
			return true, nil
		case next.hasFourSpacePrefix():
			if paused != nil {
				block.Raw = append(block.Raw, md.Run(*paused))
				block.Prose = append(block.Prose, md.Run{
					paused.Line, bytes.TrimPrefix(paused.Bytes, fourspace)})
				paused = nil
			}
			block.Raw = append(block.Raw, md.Run(next))
			block.Prose = append(block.Prose, md.Run{
				next.Line, bytes.TrimPrefix(next.Bytes, fourspace)})
			return true, nil
		// next not blank & not indented. End the block.
		default:
			if paused != nil {
				block.Raw = append(block.Raw, md.Run(*paused))
				block.Prose = append(block.Prose, md.Run{
					paused.Line, bytes.TrimPrefix(paused.Bytes, fourspace)})
			}
			ctx.Emit(block)
			ctx.Emit(md.End{})
			return false, nil
		}
	})
}
开发者ID:akavel,项目名称:vfmd,代码行数:52,代码来源:code.go

示例5: TrimBOM

func TrimBOM(b []byte, encoding string) []byte {
	bom := boms[encoding]
	if bom != nil {
		b = bytes.TrimPrefix(b, bom)
	}
	return b
}
开发者ID:fanyang01,项目名称:crawler,代码行数:7,代码来源:util.go

示例6: getMACAdress

func (d *Driver) getMACAdress() (string, error) {
	args := append(d.xhyveArgs(), "-M")

	stdout := bytes.Buffer{}

	cmd := exec.Command(os.Args[0], args...) // TODO: Should be possible without exec
	log.Debugf("Running command: %s %s", os.Args[0], args)

	cmd.Stdout = &stdout
	if err := cmd.Run(); err != nil {
		if exitErr, ok := err.(*exec.ExitError); ok {
			log.Debugf("Stderr: %s", exitErr.Stderr)
		}
		return "", err
	}

	mac := bytes.TrimPrefix(stdout.Bytes(), []byte("MAC: "))
	mac = bytes.TrimSpace(mac)

	hw, err := net.ParseMAC(string(mac))
	if err != nil {
		return "", err
	}
	return hw.String(), nil
}
开发者ID:johanneswuerbach,项目名称:docker-machine-xhyve,代码行数:25,代码来源:xhyve.go

示例7: decodeShallow

// Keeps reading shallows until a flush-pkt is found
func decodeShallow(p *Decoder) decoderStateFn {
	if !bytes.HasPrefix(p.line, shallow) {
		p.error("malformed shallow prefix, found %q... instead", p.line[:len(shallow)])
		return nil
	}
	p.line = bytes.TrimPrefix(p.line, shallow)

	if len(p.line) != hashSize {
		p.error(fmt.Sprintf(
			"malformed shallow hash: wrong length, expected 40 bytes, read %d bytes",
			len(p.line)))
		return nil
	}

	text := p.line[:hashSize]
	var h plumbing.Hash
	if _, err := hex.Decode(h[:], text); err != nil {
		p.error("invalid hash text: %s", err)
		return nil
	}

	p.data.Shallows = append(p.data.Shallows, h)

	if ok := p.nextLine(); !ok {
		return nil
	}

	if len(p.line) == 0 {
		return nil // succesfull parse of the advertised-refs message
	}

	return decodeShallow
}
开发者ID:alcortesm,项目名称:go-git,代码行数:34,代码来源:decoder.go

示例8: walkAndFindJsonFile

func walkAndFindJsonFile(path string, info os.FileInfo, err error) error {
	if !info.IsDir() {
		if strings.Contains(info.Name(), "json") {
			fmt.Println("处理文件:::" + path)
			data, err := ioutil.ReadFile(path)
			if err != nil {
				panic(err)
			}
			data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
			data, _ = GbkToUtf8(data)
			var book Book
			if err := json.Unmarshal(data, &book); err != nil {
				panic(err)
			}
			var bookName = book.Title
			var fileName = strings.Split(info.Name(), ".")[0]
			var zipFileName = strings.Split(book.ImageZipfile, ".")[0]
			if !strings.EqualFold(fileName, bookName) || !strings.EqualFold(zipFileName, bookName) {
				fmt.Println(info.Name() + ":::文件名:[" + bookName + "], zip文件名:[" + zipFileName + "]有误")
				fmt.Println(fileName + ":::文件名")
				fmt.Println(bookName + ":::书名")
				fmt.Println(zipFileName + ":::zip文件名")
				panic(info.Name())
			}
			fmt.Printf("%s 格式正确\n", path)
		}
		if _, err := CopyFile(destDir+string(os.PathSeparator)+info.Name(), path); err != nil {
			panic(err)
		}
	} else {
		fmt.Printf("%s\n", path)
	}
	return nil
}
开发者ID:nivance,项目名称:go-example,代码行数:34,代码来源:file_proc.go

示例9: stockticker

func stockticker(w http.ResponseWriter, r *http.Request) {
	// Use http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG to get a JSON response
	response, err = http.Get("http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG,NASDAQ:AAPL,NASDAQ:MSFT")
	if err != nil {
		fmt.Println(err)
	}
	defer response.Body.Close()

	// Read the data into a byte slice
	body, err = ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
	}
	// Remove whitespace from response
	data := bytes.TrimSpace(body)

	// Remove leading slashes and blank space to get byte slice that can be unmarshaled from JSON
	data = bytes.TrimPrefix(data, []byte("// "))

	// Unmarshal the JSON byte slice to a predefined struct
	err = json.Unmarshal(data, &stocks)
	if err != nil {
		fmt.Println(err)
	}

	// Parse struct data to template
	tempErr := stockTemplate.Execute(w, stocks)
	if tempErr != nil {
		http.Error(w, tempErr.Error(), http.StatusInternalServerError)
	}
}
开发者ID:tjaensch,项目名称:stockticker_google_sdk,代码行数:31,代码来源:main.go

示例10: decodeOtherWants

// Expected format: want <hash>
func (d *ulReqDecoder) decodeOtherWants() stateFn {
	if ok := d.nextLine(); !ok {
		return nil
	}

	if bytes.HasPrefix(d.line, shallow) {
		return d.decodeShallow
	}

	if bytes.HasPrefix(d.line, deepen) {
		return d.decodeDeepen
	}

	if len(d.line) == 0 {
		return nil
	}

	if !bytes.HasPrefix(d.line, want) {
		d.error("unexpected payload while expecting a want: %q", d.line)
		return nil
	}
	d.line = bytes.TrimPrefix(d.line, want)

	hash, ok := d.readHash()
	if !ok {
		return nil
	}
	d.data.Wants = append(d.data.Wants, hash)

	return d.decodeOtherWants
}
开发者ID:src-d,项目名称:go-git,代码行数:32,代码来源:ulreq_decode.go

示例11: Parse

func (p *GraphiteParser) Parse(buf []byte) ([]telegraf.Metric, error) {
	// parse even if the buffer begins with a newline
	buf = bytes.TrimPrefix(buf, []byte("\n"))

	metrics := make([]telegraf.Metric, 0)

	buffer := bytes.NewBuffer(buf)
	reader := bufio.NewReader(buffer)
	for {
		// Read up to the next newline.
		buf, err := reader.ReadBytes('\n')
		if err == io.EOF {
			return metrics, nil
		}
		if err != nil && err != io.EOF {
			return metrics, err
		}

		// Trim the buffer, even though there should be no padding
		line := strings.TrimSpace(string(buf))
		if metric, err := p.ParseLine(line); err == nil {
			metrics = append(metrics, metric)
		}
	}

}
开发者ID:henrypfhu,项目名称:telegraf,代码行数:26,代码来源:parser.go

示例12: getRepos

func getRepos(URL *url.URL) (map[string]string, error) {
	URL.RawQuery = "format=JSON"
	resp, err := http.Get(URL.String())
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	const xssTag = ")]}'\n"
	content = bytes.TrimPrefix(content, []byte(xssTag))

	m := map[string]*Project{}
	if err := json.Unmarshal(content, &m); err != nil {
		return nil, err
	}

	result := map[string]string{}
	for k, v := range m {
		result[k] = v.CloneURL
	}
	return result, nil
}
开发者ID:tadeuszwojcik,项目名称:zoekt,代码行数:27,代码来源:main.go

示例13: ReadDir

func (fs *hgFSCmd) ReadDir(path string) ([]os.FileInfo, error) {
	path = filepath.Clean(internal.Rel(path))
	// This combination of --include and --exclude opts gets all the files in
	// the dir specified by path, plus all files one level deeper (but no
	// deeper). This lets us list the files *and* subdirs in the dir without
	// needlessly listing recursively.
	cmd := exec.Command("hg", "locate", "--rev="+string(fs.at), "--include="+path, "--exclude="+filepath.Clean(path)+"/*/*/*")
	cmd.Dir = fs.dir
	out, err := cmd.CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("exec `hg cat` failed: %s. Output was:\n\n%s", err, out)
	}

	subdirs := make(map[string]struct{})
	prefix := []byte(path + "/")
	files := bytes.Split(out, []byte{'\n'})
	var fis []os.FileInfo
	for _, nameb := range files {
		nameb = bytes.TrimPrefix(nameb, prefix)
		if len(nameb) == 0 {
			continue
		}
		if bytes.Contains(nameb, []byte{'/'}) {
			subdir := strings.SplitN(string(nameb), "/", 2)[0]
			if _, seen := subdirs[subdir]; !seen {
				fis = append(fis, &util.FileInfo{Name_: subdir, Mode_: os.ModeDir})
				subdirs[subdir] = struct{}{}
			}
			continue
		}
		fis = append(fis, &util.FileInfo{Name_: filepath.Base(string(nameb))})
	}

	return fis, nil
}
开发者ID:alexsaveliev,项目名称:go-vcs,代码行数:35,代码来源:repo.go

示例14: getGoroutineID

func getGoroutineID() (uint64, error) {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	return strconv.ParseUint(string(b), 10, 64)
}
开发者ID:unchartedsoftware,项目名称:plog,代码行数:7,代码来源:log.go

示例15: checkVersionMatch

// checkVersionMatch makes sure that the go command in the path matches
// the GOROOT that will be used for building the cross compiler.
//
// This is typically not a problem when using the a release version, but
// it is easy for development environments to drift, causing unexpected
// errors.
//
// checkVersionMatch is run after the tmpGoroot is built, so the dist
// command is available to call.
func checkVersionMatch(tmpGoroot string, version []byte) error {
	if buildN {
		return nil
	}
	version = bytes.TrimPrefix(version, []byte("go version "))
	version = bytes.Trim(version, "\n")

	dist := filepath.Join(tmpGoroot, "pkg/tool/"+goEnv("GOOS")+"_"+goEnv("GOARCH")+"/dist")
	if goos == "windows" {
		dist += ".exe"
	}
	cmd := exec.Command(dist, "version")
	cmd.Dir = tmpGoroot
	cmd.Env = []string{
		"GOROOT=" + tmpGoroot,
		`PATH=` + os.Getenv("PATH"),
	}
	cmd.Env = appendCommonEnv(cmd.Env)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("cannot get cmd/dist version: %v (%s)", err, out)
	}
	out = bytes.Trim(out, "\n")

	if !bytes.HasPrefix(version, out) {
		return fmt.Errorf("Go command out of sync with GOROOT. The command `go version` reports:\n\t%s\nbut the GOROOT %q is version:\n\t%s\nRebuild Go.", version, goEnv("GOROOT"), out)
	}
	return nil
}
开发者ID:handong890,项目名称:mobile,代码行数:38,代码来源:init.go


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