package image import ( "io/ioutil" "log" "path" "time" "github.com/matoous/go-nanoid" ) // Servicer image management type Servicer interface { NewID() (string, error) AddFile(filename string, fileBytes []byte) error } // NewService new image service func NewService(repo Repo, storagePath string) *Service { return &Service{repo, storagePath, } } // Service a container for working with images type Service struct { db Repo storagePath string } // NewID create an uniqueish ID func (is *Service) NewID() (string, error) { return gonanoid.Nanoid() } // AddFile writes to disk, writes meta to db func (is *Service) AddFile(fileName string, fileBytes []byte) error { filePath := path.Join(is.storagePath, fileName) if err := ioutil.WriteFile(filePath, fileBytes, 0750); err != nil { log.Fatal(err) return err } t := time.Now().UTC() postMeta := &PostMeta{ FilePath: fileName, CreatedAt: t.Format(time.RFC3339), UserID: "1", } is.db.AddNewFile(fileName, postMeta, 946080000) if err := is.db.AddNewFile(fileName, postMeta, 946080000); err != nil { log.Fatal(err) return err } return nil }