go-cert-gen/internal/io/writer.go

46 lines
891 B
Go
Raw Normal View History

package io
import (
"fmt"
2023-03-05 15:00:53 +01:00
"log"
"os"
"gitlab.com/urkob/go-cert-gen/pkg/io"
)
type writer struct {
dirPath string
}
2023-03-05 00:05:00 +01:00
// WriteFile writes file into `w writer` directory.
// Returns outputPath and error
func (w writer) WriteFile(filename string, data []byte) (string, error) {
2023-03-05 00:05:00 +01:00
if filename == "" {
return "", fmt.Errorf("filename cannot be empty")
}
if w.dirPath == "" {
return "", fmt.Errorf("export directory cannot be empty")
}
if err := os.MkdirAll(w.dirPath, 0o755); err != nil {
return "", err
}
2023-03-05 15:00:53 +01:00
log.Println("to write file")
outputPath := w.dirPath + "/" + filename
if err := os.WriteFile(outputPath, data, 0o600); err != nil {
return "", err
}
2023-03-05 15:00:53 +01:00
log.Println("file written")
return outputPath, nil
}
func NewWriter(dirPath string) io.WriterIface {
2023-03-05 00:05:00 +01:00
return newWriter(dirPath)
}
func newWriter(dirPath string) *writer {
return &writer{
dirPath: dirPath,
}
}