From 775eb334355cdc8cdd22f8661921d7c55a066e7d Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Sat, 21 Apr 2018 19:47:44 +0200 Subject: [PATCH] [client:config] config management to get 'io.Reader' and 'io.Writer' + config directory+files management for {client.keyset} to be stored/fetched --- src/git.xdrm.io/schastsp/client/config.go | 118 ++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 src/git.xdrm.io/schastsp/client/config.go diff --git a/src/git.xdrm.io/schastsp/client/config.go b/src/git.xdrm.io/schastsp/client/config.go new file mode 100644 index 0000000..de71391 --- /dev/null +++ b/src/git.xdrm.io/schastsp/client/config.go @@ -0,0 +1,118 @@ +package client; + +import ( + "io" + "fmt" + "path/filepath" + "errors" + "os" +) + + +type config struct { + path string // absolute configuration file path + fd *os.File // file descriptor +} + +/* (1) Constructor +* +* @dir Dir path +* @name file name +* +---------------------------------------------------------*/ +func Config(dir string, name string) (*config, error) { + + inst := new(config); + + + /* (1) Check directory */ + absoluteDir, err := filepath.Abs(dir); + if err != nil { return nil, err; } + + if info, err := os.Stat(absoluteDir); err != nil { + + // fail if directory does not exist + if os.IsNotExist(err) { + + // try to create file + err2 := os.MkdirAll(absoluteDir, 0755); + + if err2 != nil { + return nil, errors.New("Cannot create missing configuration dir"); + } + + // fail if not a directory + } else if !info.Mode().IsDir() { + return nil, errors.New("Configuration dir is not a directory"); + } + + } + + + /* (2) Build full path */ + basename := filepath.Base(name); + + fullpath := fmt.Sprintf("%s/%s", absoluteDir, basename); + + + /* (3) Check file */ + info, err := os.Stat(fullpath); + if err != nil { + + // If not exists + if os.IsNotExist(err) { + + // try to create file + _, err2 := os.Create(fullpath); + + if err2 != nil { + return nil, errors.New("Cannot create missing configuration file"); + } + + } + + // fail if exists but not regular file + if !info.Mode().IsRegular() { + return nil, errors.New("Configuration file is not a regular file"); + } + + } + + fmt.Printf("hehe: %t\n", info.Mode().IsRegular()); + inst.path = fullpath + + return inst, nil + +} + + +/* (2) Get Reader on the file +* +* @return reader File reader +* NIL on error +* +---------------------------------------------------------*/ +func (c config) Reader() io.ReadCloser { + + file, err := os.Open(c.path); + if err != nil { return nil } + + return file; + +} + + +/* (3) Get Writer on the file +* +* @return reader File reader +* NIL on error +* +---------------------------------------------------------*/ +func (c config) Writer() io.WriteCloser { + + file, err := os.OpenFile(c.path, os.O_RDWR|os.O_CREATE, 0755); + if err != nil { return nil } + + return file; + +} \ No newline at end of file