Search code examples
jsongogo-gormgo-gin

How to specify path to gorm structure file


I have a Products structure:

type Products struct {
    gorm.Model
    CategoriesRefer   int64      `json:"cat_id" gorm:"column:cat_id"`
    Title             string     `json:"title" gorm:"column:title"`
    ...
    Image             string     `json:"image" gorm:"column:image"`
}

The JSON request will contain the path to the image, which is stored in another folder of my project(not in db folder), how can I specify this in the structure?


Solution

  • I believe something like this should work.

    package main
    
    import (
        "fmt"
        "os"
        "path/filepath"
    )
    
    func main() {
        ex, err := os.Executable()
        if err != nil {
            panic(err)
        }
        exPath := filepath.Dir(ex)
        imagePath := fmt.Sprintf("%s/../photos", exPath) // change photos to correct directory name
        fmt.Println("imagePath:", imagePath)
    }
    

    However as mentioned in comments this isn't a great idea as it will be relative to the directory where the compiled binary executable is located. You may want to use something like an Environment Variable to control this directory. That way way you can set it to different directories for testing, development, production, etc...