make cmd Command 时生成的文件没有内容

1. 运行环境

go version go1.17.5 darwin/amd64

2. 问题描述?

go run main.go make cmd testCommand

[app/cmd/test_command.go] created.
command name:test_command
command variable name: cmd.CmdTestCommand
please edit main.go's app.Commands slice to register command

pkg/file/file.go

// Put 将数据存入文件
func Put(data []byte, to string) error {
    err := ioutil.WriteFile(to, data, 0644)
    log.Println(ioutil.WriteFile(to, data, 0644))
    if err != nil {
        return err
    }
    return nil
}

app/cmd/make/make.go

// createFileFromStub 读取 stub 文件并进行变量替换
func createFileFromStub(filePath string, stubName string, model Model, variables ...interface{}) {
    `
    `
    `
    // 读取 stub 模板文件
    modelData, _ := stubsFS.ReadFile("stubs/"  + stubName +  ".stub")
    modelStub :=  string(modelData)

    // 对模板内容做变量替换
    for search, replace :=  range replaces {
        modelStub = strings.ReplaceAll(modelStub, search, replace)
    }
    log.Println(modelStub)
    `
    `
    `
}
go run main.go make cmd testCommand

2022/01/08 18:26:57
2022/01/08 18:26:57 <nil>
[app/cmd/test_command.go] created.
command name:test_command
command variable name: cmd.CmdTestCommand
please edit main.go's app.Commands slice to register command

3. 您期望得到的结果?

make cmd Command 时 生成的文件没有内容

4. 您实际得到的结果?

make cmd Command 时 生成的文件没有内容

Oyxiaoxi
最佳答案

注意个细节,在 11.5. key 命令一节中,如果你使用过 go run main.go key 生成 App Key,请一定将生成的 key,添加至 .env 文件中,否则将会出现

go run main.go make model project

open stubs/model/model.stub: file does not exist
exit status 1

go run main.go make model project_topic_comment

open stubs/model/model.stub: file does not exist
exit status 1

的情况!

2年前 评论
rufo 2年前
Oyxiaoxi (作者) (楼主) 2年前
讨论数量: 5
Summer

你把 app/cmd/make/make.go 文件中 createFileFromStub 里的 读取 stub 模板文件 这行修改下:

    // 读取 stub 模板文件
    modelData, err := stubsFS.ReadFile("stubs/" + stubName + ".stub")
    if err != nil {
        console.Exit(err.Error())
    }

看看有没有错误发生

2年前 评论

@Summer 按教材中的 createFileFromStub 方法修改以后,testCommand 生成的文件有内容了,往下执行 make model,可以生成 project、project_topic_comment 文件夹,但不会生成文件,且会提示模板文件不存在。

go run main.go make model project

open stubs/model/model.stub: file does not exist
exit status 1

go run main.go make model project_topic_comment

open stubs/model/model.stub: file does not exist
exit status 1
2年前 评论

注意个细节,在 11.5. key 命令一节中,如果你使用过 go run main.go key 生成 App Key,请一定将生成的 key,添加至 .env 文件中,否则将会出现

go run main.go make model project

open stubs/model/model.stub: file does not exist
exit status 1

go run main.go make model project_topic_comment

open stubs/model/model.stub: file does not exist
exit status 1

的情况!

2年前 评论
rufo 2年前
Oyxiaoxi (作者) (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!