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


Golang path.Ext函数代码示例

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


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

示例1: ConvertToMP3

// ConvertToMP3 converts given file into .mp3 file
// Example: ConvertToMP3("oldAudio", "newAudio")
// Result: newAudio.mp3
// If only one argument is passed, than result will have the same name
func ConvertToMP3(filenames ...string) error {
	var toFilename string
	var fromFilename string = filenames[0]
	switch len(filenames) {
	case 1:
		toFilename = cutExtension(filenames[0])
		break
	case 0:
		return errors.New("error: no arguements passed")
	default:
		toFilename = cutExtension(filenames[1])
	}
	os.Remove(toFilename + ".mp3")
	// Convert to MP3
	switch path.Ext(fromFilename) {
	case ".amr":
		comm := exec.Command("ffmpeg", "-i", fromFilename, "-ar", AudioSamplingRateMP3, toFilename+".mp3")
		if err := comm.Run(); err != nil {
			return ConvertError
		}
	default:
		return fmt.Errorf("Unsupported format: %v", path.Ext(fromFilename))
	}
	return nil
}
开发者ID:seka17,项目名称:bracelet,代码行数:29,代码来源:convert.go

示例2: Report

// When a test is skipped or fails, runtime.Goexit() is called which destroys the callstack.
// This means the name of the test case is lost, so we need to grab a copy of pc before.
func Report(t testing.TB) {
	// If the goroutine panics, Fatal()s, or Skip()s, the function name is at the 3rd callstack
	// layer.  On success, its at 1st.  Since it's hard to check which happened, just try both.
	pcs := make([]uintptr, 10)
	total := runtime.Callers(1, pcs)
	var name string
	for _, pc := range pcs[:total] {
		fn := runtime.FuncForPC(pc)
		fullName := fn.Name()
		if strings.HasPrefix(path.Ext(fullName), ".Test") {
			// Skip the leading .
			name = string([]byte(path.Ext(fullName))[1:])
			break
		}
	}
	if name == "" {
		return
	}

	allCaseInfos.lock.Lock()
	defer allCaseInfos.lock.Unlock()
	allCaseInfos.Cases = append(allCaseInfos.Cases, &caseInfo{
		Name:    name,
		Passed:  !t.Failed() && !t.Skipped(),
		Skipped: t.Skipped(),
		Fatal:   t.Failed() && !strings.HasPrefix(name, "TestSoon"),
	})
}
开发者ID:ConfusedReality,项目名称:pkg_network_grpc,代码行数:30,代码来源:testsuite.go

示例3: GetRequestedEndPoint

func (this *SunnyEndPoint) GetRequestedEndPoint(r *http.Request, upath []string, data []string) *RequestedEndPoint {
	handlers := this.Handlers()
	if h, exists := handlers[r.Method]; exists && h != nil {
		var pdata = make(map[string]string)
		for i, value := range data {
			if this.varnames[i] != "_" {
				pdata[this.varnames[i]] = value
			}
		}

		ext := ""
		lastele := len(upath) - 1

		if lastele >= 0 && strings.Contains(upath[lastele], ".") {
			ext = path.Ext(upath[lastele])
			upath[lastele] = strings.TrimSuffix(upath[lastele], ext)
		} else {
			ext = path.Ext(strings.TrimRight(r.URL.Path, "/"))
		}

		return &RequestedEndPoint{
			Ext:      ext,
			UPath:    web.UPath(upath),
			PData:    web.PData(pdata),
			Method:   r.Method,
			Handler:  h,
			EndPoint: this,
		}
	}

	return nil
}
开发者ID:zaolab,项目名称:sunnified,代码行数:32,代码来源:route.go

示例4: ReadFile

// Reads an array from a file.
func ReadFile(fname string) *host.Array {
	readFunc, ok := inputFormats[path.Ext(fname)]
	if !ok {
		panic(InputErrF("Can not load file with extension ", path.Ext(fname)))
	}
	return readFunc(fname)
}
开发者ID:LStoleriu,项目名称:hotspin,代码行数:8,代码来源:input.go

示例5: AddFile

// AddFile saves to Response.Files preparing for Pipeline
func (self *Response) AddFile(name ...string) {
	file := map[string]interface{}{
		"Body": self.Response.Body,
	}

	_, s := path.Split(self.GetUrl())
	n := strings.Split(s, "?")[0]

	// 初始化
	baseName := strings.Split(n, ".")[0]
	ext := path.Ext(n)

	if len(name) > 0 {
		_, n = path.Split(name[0])
		if baseName2 := strings.Split(n, ".")[0]; baseName2 != "" {
			baseName = baseName2
		}
		if ext == "" {
			ext = path.Ext(n)
		}
	}

	if ext == "" {
		ext = ".html"
	}

	file["Name"] = baseName + ext

	self.files = append(self.files, file)
}
开发者ID:no2key,项目名称:pholcus-1,代码行数:31,代码来源:response.go

示例6: openSource

func (fs *gopherJSFS) openSource(path string) (http.File, error) {
	f, err := fs.source.Open(path)
	if err != nil {
		return nil, err
	}

	fi, err := f.Stat()
	if err != nil {
		f.Close()
		return nil, err
	}

	switch {
	// Files with .go and ".inc.js" extensions are consumed and no longer exist
	// in output filesystem.
	case !fi.IsDir() && pathpkg.Ext(fi.Name()) == ".go":
		fallthrough
	case !fi.IsDir() && strings.HasSuffix(fi.Name(), ".inc.js"):
		f.Close()
		return nil, &os.PathError{Op: "open", Path: path, Err: os.ErrNotExist}
	case !fi.IsDir():
		return f, nil
	}
	defer f.Close()

	fis, err := f.Readdir(0)
	if err != nil {
		return nil, err
	}

	// Include all subfolders, non-.go files.
	var entries []os.FileInfo
	var haveGo []os.FileInfo
	for _, fi := range fis {
		switch {
		case !fi.IsDir() && pathpkg.Ext(fi.Name()) == ".go":
			haveGo = append(haveGo, fi)
		case !fi.IsDir() && strings.HasSuffix(fi.Name(), ".inc.js"):
			// TODO: Handle ".inc.js" files correctly.
			entries = append(entries, fi)
		default:
			entries = append(entries, fi)
		}
	}

	// If it has any .go files, present the Go package compiled with GopherJS as an additional virtual file.
	if len(haveGo) > 0 {
		entries = append(entries, &file{
			name:    fi.Name() + ".js",
			size:    0,           // TODO.
			modTime: time.Time{}, // TODO.
		})
	}

	return &dir{
		name:    fi.Name(),
		entries: entries,
		modTime: fi.ModTime(),
	}, nil
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:60,代码来源:vfs.go

示例7: ConvertToM4A

// ConvertToM4A converts given file into .m4a file
// Example: ConvertToM4A("oldAudio", "newAudio")
// Result: newAudio.M4A
// If only one argument is passed, than result will have the same name
func ConvertToM4A(fromFilename string, length string) error {
	toFilename := cutExtension(fromFilename)
	fmt.Println(fromFilename, toFilename, length)

	os.Remove(toFilename + ".m4a")
	// Convert to M4A
	switch path.Ext(fromFilename) {
	case ".amr":
		// fileSize (in bytes) / bit-rate (bits/secs)*8
		// ffmpeg -t 2 -i test.amr -ar 8k test1.m4a
		var comm *exec.Cmd
		if length != "" {
			fmt.Println("ffmpeg", "-t", length, "-i", fromFilename, toFilename+".m4a")
			comm = exec.Command("ffmpeg", "-t", length, "-i", fromFilename, toFilename+".m4a")
		} else {
			comm = exec.Command("ffmpeg", "-i", fromFilename, toFilename+".m4a")
		}

		if err := comm.Run(); err != nil {
			return ConvertError
		}
	default:
		return fmt.Errorf("Unsupported format: %v", path.Ext(fromFilename))
	}
	return nil
}
开发者ID:seka17,项目名称:bracelet,代码行数:30,代码来源:convert.go

示例8: getKey

// This getKey interprets key IDs as paths, and loads private keys from the
// specified file
func getKey(keyid string) (crypto.PrivateKey, error) {
	fileContents, err := ioutil.ReadFile(keyid)
	if err != nil {
		return nil, err
	}
	if path.Ext(keyid) == ".ed25519secret" {
		if got, want := len(fileContents), ed25519.PrivateKeySize; got != want {
			return nil, fmt.Errorf("ed25519 private key %s has wrong size %d (want %d)", keyid, got, want)
		}
		var keyArray [ed25519.PrivateKeySize]uint8
		copy(keyArray[:], fileContents)
		return &keyArray, nil
	} else if path.Ext(keyid) == ".vrfsecret" {
		if got, want := len(fileContents), vrf.SecretKeySize; got != want {
			return nil, fmt.Errorf("VRF private key %s has wrong size %d (want %d)", keyid, got, want)
		}
		var keyArray [vrf.SecretKeySize]uint8
		copy(keyArray[:], fileContents)
		return &keyArray, nil
	} else {
		keyPEM := fileContents
		var keyDER *pem.Block
		for {
			keyDER, keyPEM = pem.Decode(keyPEM)
			if keyDER == nil {
				return nil, fmt.Errorf("failed to parse key PEM in %s", keyid)
			}
			if keyDER.Type == "PRIVATE KEY" || strings.HasSuffix(keyDER.Type, " PRIVATE KEY") {
				break
			}
		}
		return parsePrivateKey(keyDER.Bytes)
	}
}
开发者ID:yahoo,项目名称:coname,代码行数:36,代码来源:main.go

示例9: requiredPaths

func (s *processedAsset) requiredPaths(rx *regexp.Regexp) ([]string, error) {
	f, err := os.Open(s.static.pathname)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	buf := bufio.NewReader(f)
	paths := make([]string, 0)
	for {
		line, err := buf.ReadString('\n')
		if err == io.EOF {
			break
		} else if err != nil {
			return nil, err
		}
		if strings.TrimSpace(line) != "" && !strings.HasPrefix(line, "//") {
			break
		}
		matches := rx.FindStringSubmatch(line)
		if len(matches) > 1 {
			match := matches[1]
			if path.Ext(match) == "" {
				match += path.Ext(s.static.logical)
			}
			paths = append(paths, match)
		}
	}
	return paths, nil
}
开发者ID:alexcrichton,项目名称:go-paste,代码行数:29,代码来源:processed_asset.go

示例10: TypeByExtension

// TypeByExtension returns the MIME type associated with the file extension ext.
// 获取文件类型,选项ContentType使用
func TypeByExtension(filePath string) string {
	typ := mime.TypeByExtension(path.Ext(filePath))
	if typ == "" {
		typ = extToMimeType[strings.ToLower(path.Ext(filePath))]
	}
	return typ
}
开发者ID:pombredanne,项目名称:dockyard,代码行数:9,代码来源:mime.go

示例11: main

func main() {
	argsWithoutProg := os.Args[1:]
	if len(argsWithoutProg) <= 0 {
		fmt.Println("Please enter a directory or file path.\r\[email protected]")
		return
	}
	target, err := os.Stat(argsWithoutProg[0])
	if os.IsNotExist(err) {
		fmt.Printf("No such file or directory: %s", argsWithoutProg[0])
		return
	}

	//process directory
	if target.IsDir() {
		files, _ := ioutil.ReadDir(argsWithoutProg[0])
		for _, file := range files {
			if file.IsDir() {
				continue
			} else {
				filePath := path.Join(argsWithoutProg[0], file.Name())
				if path.Ext(filePath) == FILE_EXT {
					PatchFile(filePath)
				}
			}
		}
	} else {
		if path.Ext(argsWithoutProg[0]) == FILE_EXT {
			PatchFile(argsWithoutProg[0])
		}
	}
}
开发者ID:kingpro,项目名称:youkuMP4Patcher,代码行数:31,代码来源:patcher.go

示例12: getTemplates

func getTemplates() (*template.Template, error) {
	t := template.New("")
	root := "app/tpl"
	err := filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
		if info.IsDir() {
			return nil
		}

		if path.Ext(p) != ".tpl" {
			return nil
		}

		if err != nil {
			return err
		}

		contents, err := ioutil.ReadFile(p)
		if err != nil {
			return err
		}

		nm := strings.Replace(p, "\\", "/", -1)
		nm = nm[len(root):]
		nm = nm[:len(nm)-len(path.Ext(nm))]

		child := t.New(nm)
		_, err = child.Parse(string(contents))

		return err
	})
	return t, err
}
开发者ID:badgerodon,项目名称:go,代码行数:32,代码来源:templates.go

示例13: detectContentType

func (r *Response) detectContentType() (sure bool) {
	if r.CertainType {
		return true
	}
	defer func() { r.CertainType = sure }()

	if t := r.Header.Get("Content-Type"); t != "" {
		r.ContentType = t
		return true
	}
	if r.NewURL != nil || r.ContentLocation != nil {
		var pth, ext string
		if r.NewURL != nil {
			pth = r.NewURL.Path
			ext = path.Ext(pth)
		}
		if ext == "" && r.ContentLocation != nil {
			pth = r.ContentLocation.Path
			ext = path.Ext(pth)
		}
		if ext != "" {
			if t := mime.TypeByExtension(ext); t != "" {
				r.ContentType = t
				return true
			}
		} else if strings.HasSuffix(pth, "/") {
			r.ContentType = "text/html"
			return false
		}
	}
	r.ContentType = string(media.UNKNOWN)
	return false
}
开发者ID:fanyang01,项目名称:crawler,代码行数:33,代码来源:fetch.go

示例14: isYaml

func isYaml(filename string) bool {
	if path.Ext(filename) == ".yml" || path.Ext(filename) == ".yaml" {
		return true
	}

	return false
}
开发者ID:bernardolins,项目名称:godfather,代码行数:7,代码来源:finder.go

示例15: Handler

func Handler(nc *blobserv.Client, w http.ResponseWriter, r *http.Request) {
	defer util.DeferWrite(w)
	c = nc

	tmpl := template.Must(template.ParseFiles(appserv.Static("pics/index.tmpl")))

	if picIndex == nil {
		loadPicIndex()
	}
	updateIndex()

	pth := strings.Trim(r.URL.Path, "/")
	if pth == "pics" {
		links := picLinks(picIndex.Newest(10))
		err := tmpl.Execute(w, links)
		util.Check(err)
	} else if strings.HasPrefix(pth, "pics/ref/") {
		ref := path.Base(pth)
		ref = ref[:len(ref)-len(path.Ext(ref))]

		fblob, err := c.ObjectTip(ref)
		util.Check(err)

		m, data, err := c.ReconstituteFile(fblob.Ref())
		util.Check(err)

		ext := path.Ext(m.Name)
		w.Header().Set("Content-Type", mime.TypeByExtension(ext))
		w.Write(data)
	} else {
		err := util.LoadStatic(appserv.Static(pth), w)
		util.Check(err)
	}
}
开发者ID:rwcarlsen,项目名称:cas,代码行数:34,代码来源:pics.go


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