github.com/yoogoc/kratos-scaffold@v0.0.0-20240402032722-a538b3c18955/project_generator/log.go (about)

     1  package project_generator
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"os"
     7  	"path"
     8  	"text/template"
     9  
    10  	"github.com/yoogoc/kratos-scaffold/pkg/util"
    11  )
    12  
    13  type LogTmpl struct {
    14  	AppPkgPath string
    15  	LogPath    string
    16  	ModName    string
    17  }
    18  
    19  type LogTmplOption func(*LogTmpl)
    20  
    21  func NewLogTmpl(appPkgPath, logPath string, options ...LogTmplOption) *LogTmpl {
    22  	st := &LogTmpl{
    23  		AppPkgPath: appPkgPath,
    24  		LogPath:    logPath,
    25  		ModName:    util.ModName(),
    26  	}
    27  	for _, option := range options {
    28  		option(st)
    29  	}
    30  	return st
    31  }
    32  
    33  func (st LogTmpl) Generate() error {
    34  	fmt.Println("generate log/log.go ...")
    35  	buf := new(bytes.Buffer)
    36  	tmpl, err := template.New("logTmpl").Parse(logTmpl)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	if err := tmpl.Execute(buf, st); err != nil {
    41  		return err
    42  	}
    43  	if err := os.WriteFile(path.Join(st.LogPath, "log.go"), buf.Bytes(), 0o644); err != nil {
    44  		return err
    45  	}
    46  	return nil
    47  }