美文网首页
Golang 根据日期创建文件夹

Golang 根据日期创建文件夹

作者: 路过麦田 | 来源:发表于2017-04-11 11:08 被阅读383次

在一些web应用中,往往会根据当前日期创建文件夹,来保存用户的文件等信息,比如

static/product/20170410/a.jpg
static/product/20170411/b.jpg

获取日期并创建文件夹这个过程中可能会遇到坑,比如创建的文件夹没有写入的权限,下面给出一段代码,可以解决这个问题


import (
    "os"
    "path/filepath"
    "time"
)

// CreateDateDir 根据当前日期来创建文件夹
func CreateDateDir(basePath string) string {
    folderName := time.Now().Format("20060102")
    folderPath := filepath.Join(basePath, folderName)
    if _, err := os.Stat(folderPath); os.IsNotExist(err) {
        // 必须分成两步
        // 先创建文件夹
        os.Mkdir(folderPath, 0777)
        // 再修改权限
        os.Chmod(folderPath, 0777)
    }
    return folderPath
}

http://studygolang.com/topics/33 这上面也有解决办法,一种就是上面的两步走,另一种就是利用修改掩码

import (
    "os"
    "path/filepath"
    "time"
    "syscall"
)

// CreateDateDir 根据当前日期来创建文件夹
func CreateDateDir(basePath string) string {
    folderName := time.Now().Format("20060102")
    folderPath := filepath.Join(basePath, folderName)
    if _, err := os.Stat(folderPath); os.IsNotExist(err) {
        oldMask := syscall.Umask(0)
        os.Mkdir(folderPath, os.ModePerm)
        syscall.Umask(oldMask)
    }
    return folderPath
}

相关文章

网友评论

      本文标题:Golang 根据日期创建文件夹

      本文链接:https://www.haomeiwen.com/subject/yjyyattx.html