本文整理汇总了Golang中path/filepath.Split函数的典型用法代码示例。如果您正苦于以下问题:Golang Split函数的具体用法?Golang Split怎么用?Golang Split使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Split函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: generateJSON
func generateJSON(path string, distPath string) {
var obj map[string]interface{}
baseURL := fmt.Sprintf("%v://%v%v", *protocol, *host, path)
fileFmt := "%v/%v"
time.Sleep(100 * time.Millisecond)
_, jsonD, _ := cr.HTTPDataMethod(cr.HTTPGetStr, baseURL, "")
err := json.Unmarshal([]byte(jsonD), &obj)
if err != nil {
log.Fatal(err)
}
var prefix, p1, file string
for i, v := range obj["apis"].([]interface{}) {
casted := v.(map[string]interface{})
url1 := fmt.Sprintf("%v%v", baseURL, casted["path"])
_, u, _ := cr.HTTPDataMethod(cr.HTTPGetStr, url1, "")
p1, file = filepath.Split(fmt.Sprintf("%v", casted["path"]))
if i == 0 {
prefix = strings.Replace(p1, "/", distPath, 1)
err := os.MkdirAll(prefix, 0777)
if err != nil {
log.Fatalf("Fatal error while generating static JSON path: %v", err)
}
}
ioutil.WriteFile(fmt.Sprintf(fileFmt, prefix, file), []byte(u), 0777)
}
_, file = filepath.Split(path)
prefix1 := strings.Replace(p1, "/", "/../", 1)
obj["apiVersion"] = "2.02"
a := obj["info"].(map[string]interface{})
a["title"] = "Libsecurity API"
j, _ := json.Marshal(obj)
newS := strings.Replace(string(j), p1, prefix1, -1)
ioutil.WriteFile(fmt.Sprintf(fileFmt, distPath, file), []byte(newS), 0777)
}
示例2: Navigate
func (l *Location) Navigate(path string) *Location {
r := New()
if is_remote(path) {
u, _ := url.Parse(path)
dir, filename := filepath.Split(u.Path)
u.Path = dir
r.Dir = u.String()
r.Filename = filename
} else if is_relative(path) {
dir, filename := filepath.Split(path)
if is_remote(l.Dir) {
u, _ := url.Parse(l.Dir)
u.Path = filepath.Join(u.Path, dir) + "/"
r.Dir = u.String()
} else {
r.Dir = filepath.Join(l.Dir, dir) + "/"
}
r.Filename = filename
} else {
dir, filename := filepath.Split(path)
r.Dir = dir
r.Filename = filename
}
return r
}
示例3: NewTagEntry
// NewTagEntry creates a new ArchiveEntry for the given values.
func NewTagEntry(file, title string) *TagEntry {
url := file + ".html"
// Not all pages have a metadata title defined.
// Use the page url instead, after we prettify it a bit.
if len(title) == 0 {
title = file
if strings.HasSuffix(title, "/index") {
title, _ = filepath.Split(title)
}
if title == "/" {
title = "Home"
}
}
// If the url ends with /index.html, we strip off the index part.
// It just takes up unnecessary bytes in the output and
// `foo/bar/` looks better than `foo/bar/index.html`.
if strings.HasSuffix(url, "/index.html") {
url, _ = filepath.Split(url)
}
te := new(TagEntry)
te.Url = template.HTMLAttr(url)
te.Title = template.HTMLAttr(title)
return te
}
示例4: Link
// Link creates the ChildDirs and ChildFiles links in all EmbeddedDir's
func (e *EmbeddedBox) Link() {
for path, ed := range e.Dirs {
fmt.Println(path)
ed.ChildDirs = make([]*EmbeddedDir, 0)
ed.ChildFiles = make([]*EmbeddedFile, 0)
}
for path, ed := range e.Dirs {
parentDirpath, _ := filepath.Split(path)
if strings.HasSuffix(parentDirpath, "/") {
parentDirpath = parentDirpath[:len(parentDirpath)-1]
}
parentDir := e.Dirs[parentDirpath]
if parentDir == nil {
panic("parentDir `" + parentDirpath + "` is missing in embedded box")
}
parentDir.ChildDirs = append(parentDir.ChildDirs, ed)
}
for path, ef := range e.Files {
dirpath, _ := filepath.Split(path)
if strings.HasSuffix(dirpath, "/") {
dirpath = dirpath[:len(dirpath)-1]
}
dir := e.Dirs[dirpath]
if dir == nil {
panic("dir `" + dirpath + "` is missing in embedded box")
}
dir.ChildFiles = append(dir.ChildFiles, ef)
}
}
示例5: genCertPair
// genCertPair generates a key/cert pair to the paths provided.
func genCertPair(certFile, keyFile string) error {
log.Infof("Generating TLS certificates...")
// Create directories for cert and key files if they do not yet exist.
certDir, _ := filepath.Split(certFile)
keyDir, _ := filepath.Split(keyFile)
if err := os.MkdirAll(certDir, 0700); err != nil {
return err
}
if err := os.MkdirAll(keyDir, 0700); err != nil {
return err
}
// Generate cert pair.
org := "btcwallet autogenerated cert"
validUntil := time.Now().Add(10 * 365 * 24 * time.Hour)
cert, key, err := btcutil.NewTLSCertPair(org, validUntil, nil)
if err != nil {
return err
}
// Write cert and key files.
if err = ioutil.WriteFile(certFile, cert, 0666); err != nil {
return err
}
if err = ioutil.WriteFile(keyFile, key, 0600); err != nil {
os.Remove(certFile)
return err
}
log.Infof("Done generating TLS certificates")
return nil
}
示例6: downloadFile
func downloadFile(furl string, ignoreTLS bool, cRoot string) ([]byte, error) {
parsedURL, err := url.Parse(furl)
// explicit file scheme ?
if parsedURL.Scheme == "file" {
return ioutil.ReadFile(parsedURL.RequestURI())
} else if cRoot != "" { // check cache on local file system
path, name := filepath.Split(parsedURL.RequestURI())
fname := filepath.Join(cRoot+path, name)
log.Println("attempting to load from cache: ", fname)
b, err := ioutil.ReadFile(fname)
if err == nil {
log.Println("file loaded from cache as: ", fname)
return b, nil
} else if os.IsNotExist(err) {
log.Println("not in cache: fname")
} else {
log.Println("cache load failed: ", err)
}
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: ignoreTLS,
},
Dial: dialTimeout,
}
client := &http.Client{Transport: tr}
resp, err := client.Get(furl)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// cache on local file system
if cRoot != "" {
path, name := filepath.Split(parsedURL.RequestURI())
fp := cRoot + path
err := os.MkdirAll(fp, 0777)
if err != nil {
return nil, err
}
fname := filepath.Join(fp, name)
err = ioutil.WriteFile(fname, data, 0644)
if err != nil {
return nil, err
}
log.Println("file saved in cache as: ", fname)
}
return data, nil
}
示例7: MoveTo
// MoveTo moves named file or directory to trash.
func MoveTo(name string) error {
name = filepath.Clean(name)
home := os.Getenv("HOME")
dir, file := filepath.Split(name)
target := filepath.Join(home, ".Trash", file)
// TODO: If target name exists in Trash, come up with a unique one (perhaps append a timestamp) instead of overwriting.
// TODO: Support OS X "Put Back". Figure out how it's done and do it.
err := os.Rename(name, target)
if err != nil {
return err
}
// If directory became empty, remove it (recursively up).
for {
// Ensure it's an empty directory.
if dirEntries, err := ioutil.ReadDir(dir); err != nil || len(dirEntries) != 0 {
break
}
// Remove directory if it's (now) empty.
err := os.Remove(dir)
if err != nil {
break
}
dir, _ = filepath.Split(dir)
}
return nil
}
示例8: NewArchiveEntry
// NewArchiveEntry creates a new ArchiveEntry for the given values.
func NewArchiveEntry(file, title, desc string, stamp time.Time) *ArchiveEntry {
url := file + ".html"
// Not all pages have a metadata title defined.
// Use the page url instead, after we prettify it a bit.
if len(title) == 0 {
title = file
if strings.HasSuffix(title, "/index") {
title, _ = filepath.Split(title)
}
if title == "/" {
title = "Home"
}
}
// If the url ends with /index.html, we strip off the index part.
// It just takes up unnecessary bytes in the output and
// `foo/bar/` looks better than `foo/bar/index.html`.
if strings.HasSuffix(url, "/index.html") {
url, _ = filepath.Split(url)
}
ae := new(ArchiveEntry)
ae.Url = template.HTMLAttr(url)
ae.Title = template.HTMLAttr(title)
ae.Description = template.HTMLAttr(desc)
ae.Stamp = stamp
return ae
}
示例9: GetMp3Tags
// GetMp3Tags returns a FileTags struct with
// all the information obtained from the tags in the
// MP3 file.
// Includes the Artist, Album and Song and defines
// default values if the values are missing.
// If the tags are missing, the default values will
// be stored on the file.
// If the tags are obtained correctly the first
// return value will be nil.
func GetMp3Tags(path string) (error, FileTags) {
mp3File, err := id3.Open(path)
if err != nil {
_, file := filepath.Split(path)
extension := filepath.Ext(file)
songTitle := file[0 : len(file)-len(extension)]
return err, FileTags{songTitle, "unknown", "unknown"}
}
defer mp3File.Close()
title := mp3File.Title()
if title == "" || title == "unknown" {
_, file := filepath.Split(path)
extension := filepath.Ext(file)
title = file[0 : len(file)-len(extension)]
mp3File.SetTitle(title)
}
artist := mp3File.Artist()
if artist == "" {
artist = "unknown"
mp3File.SetArtist(artist)
}
album := mp3File.Album()
if album == "" {
album = "unknown"
mp3File.SetAlbum(album)
}
ft := FileTags{title, artist, album}
return nil, ft
}
示例10: BenchmarkCFuseThreadedStat
func BenchmarkCFuseThreadedStat(b *testing.B) {
b.StopTimer()
wd, _ := os.Getwd()
fileList := wd + "/testpaths.txt"
lines := ReadLines(fileList)
unique := map[string]int{}
for _, l := range lines {
unique[l] = 1
dir, _ := filepath.Split(l)
for dir != "/" && dir != "" {
unique[dir] = 1
dir = filepath.Clean(dir)
dir, _ = filepath.Split(dir)
}
}
out := []string{}
for k := range unique {
out = append(out, k)
}
f, err := ioutil.TempFile("", "")
if err != nil {
b.Fatalf("failed: %v", err)
}
sort.Strings(out)
for _, k := range out {
f.Write([]byte(fmt.Sprintf("/%s\n", k)))
}
f.Close()
mountPoint := testutil.TempDir()
cmd := exec.Command(wd+"/cstatfs",
"-o",
"entry_timeout=0.0,attr_timeout=0.0,ac_attr_timeout=0.0,negative_timeout=0.0",
mountPoint)
cmd.Env = append(os.Environ(),
fmt.Sprintf("STATFS_INPUT=%s", f.Name()))
cmd.Start()
bin, err := exec.LookPath("fusermount")
if err != nil {
b.Fatalf("failed: %v", err)
}
stop := exec.Command(bin, "-u", mountPoint)
if err != nil {
b.Fatalf("failed: %v", err)
}
defer stop.Run()
time.Sleep(100 * time.Millisecond)
os.Lstat(mountPoint)
threads := runtime.GOMAXPROCS(0)
if err := TestingBOnePass(b, threads, fileList, mountPoint); err != nil {
log.Fatalf("TestingBOnePass %v", err)
}
}
示例11: trimWebPath
func trimWebPath(p string) string {
d, f := filepath.Split(p)
clean := strings.TrimSuffix(d, string(filepath.Separator))
_, f1 := filepath.Split(clean)
if f == strings.TrimSuffix(f1, filepath.Ext(clean)) {
return clean
}
return p
}
示例12: up
func (fc *FileChooser) up() {
path := fc.filename.GetText()
dir, file := filepath.Split(path)
if file == "" {
dir, file = filepath.Split(path[0 : len(path)-1])
}
fc.filename.SetText(dir)
fc.setList()
}
示例13: uploadDirTree
func (ftp *FTP) uploadDirTree(localDir string, excludedDirs sort.StringSlice, callback Callback, n *int) (err error) {
_, dir := filepath.Split(localDir)
ftp.writeInfo("The directory where to upload is:", dir)
if _, err = ftp.Mkd(dir); err != nil {
return
}
_, err = ftp.Cwd(dir)
if err != nil {
ftp.writeInfo(fmt.Sprintf("An error occurred while CWD, err: %s.", err))
return
}
defer ftp.Cwd("..")
globSearch := filepath.Join(localDir, "*")
ftp.writeInfo("Looking up files in", globSearch)
var files []string
files, err = filepath.Glob(globSearch) // find all files in folder
if err != nil {
return
}
ftp.writeInfo("Found", len(files), "files")
sort.Strings(files) // sort by name
for _, s := range files {
_, fname := filepath.Split(s) // find file name
localPath := filepath.Join(localDir, fname)
ftp.writeInfo("Uploading file or dir:", localPath)
var f os.FileInfo
if f, err = os.Stat(localPath); err != nil {
return
}
if !f.IsDir() {
err = ftp.UploadFile(fname, localPath, false, callback) // always binary upload
if err != nil {
return
}
*n += 1 // increment
} else {
if len(excludedDirs) > 0 {
ftp.writeInfo("Checking folder name:", fname)
lfname := strings.ToLower(fname)
idx := sort.SearchStrings(excludedDirs, lfname)
if idx < len(excludedDirs) && excludedDirs[idx] == lfname {
ftp.writeInfo("Excluding folder:", s)
continue
}
}
if err = ftp.uploadDirTree(localPath, excludedDirs, callback, n); err != nil {
return
}
}
}
return
}
示例14: BenchmarkCFuseThreadedStat
func BenchmarkCFuseThreadedStat(b *testing.B) {
b.StopTimer()
lines := GetTestLines()
unique := map[string]int{}
for _, l := range lines {
unique[l] = 1
dir, _ := filepath.Split(l)
for dir != "/" && dir != "" {
unique[dir] = 1
dir = filepath.Clean(dir)
dir, _ = filepath.Split(dir)
}
}
out := []string{}
for k := range unique {
out = append(out, k)
}
f, err := ioutil.TempFile("", "")
CheckSuccess(err)
sort.Strings(out)
for _, k := range out {
f.Write([]byte(fmt.Sprintf("/%s\n", k)))
}
f.Close()
mountPoint, _ := ioutil.TempDir("", "stat_test")
wd, _ := os.Getwd()
cmd := exec.Command(wd+"/cstatfs",
"-o",
"entry_timeout=0.0,attr_timeout=0.0,ac_attr_timeout=0.0,negative_timeout=0.0",
mountPoint)
cmd.Env = append(os.Environ(),
fmt.Sprintf("STATFS_INPUT=%s", f.Name()),
fmt.Sprintf("STATFS_DELAY_USEC=%d", delay/time.Microsecond))
cmd.Start()
bin, err := exec.LookPath("fusermount")
CheckSuccess(err)
stop := exec.Command(bin, "-u", mountPoint)
CheckSuccess(err)
defer stop.Run()
for i, l := range lines {
lines[i] = filepath.Join(mountPoint, l)
}
// Wait for the daemon to mount.
time.Sleep(200 * time.Millisecond)
ttl := time.Millisecond * 100
threads := runtime.GOMAXPROCS(0)
results := TestingBOnePass(b, threads, time.Duration((ttl*12)/10), lines)
AnalyzeBenchmarkRuns("CFuse", results)
}
示例15: extractKernelImages
func (d *Driver) extractKernelImages() error {
log.Debugf("Mounting %s", isoFilename)
volumeRootDir := d.ResolveStorePath(isoMountPath)
err := hdiutil("attach", d.ResolveStorePath(isoFilename), "-mountpoint", volumeRootDir)
if err != nil {
return err
}
log.Debugf("Extracting Kernel Options...")
if err := d.extractKernelOptions(); err != nil {
return err
}
defer func() error {
log.Debugf("Unmounting %s", isoFilename)
return hdiutil("detach", volumeRootDir)
}()
if d.BootKernel == "" && d.BootInitrd == "" {
err = filepath.Walk(volumeRootDir, func(path string, f os.FileInfo, err error) error {
if kernelRegexp.MatchString(path) {
d.BootKernel = path
_, d.Vmlinuz = filepath.Split(path)
}
if strings.Contains(path, "initrd") {
d.BootInitrd = path
_, d.Initrd = filepath.Split(path)
}
return nil
})
}
if err != nil {
if err != nil || d.BootKernel == "" || d.BootInitrd == "" {
err = fmt.Errorf("==== Can't extract Kernel and Ramdisk file ====")
return err
}
}
dest := d.ResolveStorePath(d.Vmlinuz)
log.Debugf("Extracting %s into %s", d.BootKernel, dest)
if err := mcnutils.CopyFile(d.BootKernel, dest); err != nil {
return err
}
dest = d.ResolveStorePath(d.Initrd)
log.Debugf("Extracting %s into %s", d.BootInitrd, dest)
if err := mcnutils.CopyFile(d.BootInitrd, dest); err != nil {
return err
}
return nil
}