title: Connecting Gorm and Gin Golang
body: <p>I am trying to create an API with <code>Go</code>, <code>gorm</code> and <code>gin</code>. However, using a direct SQL query did work, but it became too cumbersome and I decided to leverage <code>gorm</code> which is fantastic. However after my implementation, I am unable to get the project up again and keep getting error</p>
  <blockquote>
  <p>panic: runtime error: invalid memory address or nil pointer
  dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0xb0
  pc=0x137b606]</p>
  </blockquote>
  <p>I have pasted my code with packages here. I would be glad if someone could point me to the issue.</p>
  <p><strong>PostgresDoa.go</strong></p>
  <pre><code>package postgres
  
  import (
      &quot;fmt&quot;
      &quot;log&quot;
      &quot;net/http&quot;
  
      &quot;github.com/AdieOlami/bookstore_users-api/domain/users&quot;
      &quot;github.com/gin-gonic/gin&quot;
      &quot;github.com/jinzhu/gorm&quot;
  )
  
  type Sever struct {
      DB     *gorm.DB
      Router *gin.Engine
  }
  
  func (server *Sever) Initialize(Dbdriver, DbUser, DbPassword, DbPort, DbHost, DbName string) {
      var err error
  
      if Dbdriver == &quot;mysql&quot; {
          DBURL := fmt.Sprintf(&quot;%s:%s@tcp(%s:%s)/%s?charset=utf8&amp;parseTime=True&amp;loc=Local&quot;, DbUser, DbPassword, DbHost, DbPort, DbName)
          server.DB, err = gorm.Open(Dbdriver, DBURL)
          if err != nil {
              fmt.Printf(&quot;Cannot connect to %s database&quot;, Dbdriver)
              log.Fatal(&quot;This is the error:&quot;, err)
          } else {
              fmt.Printf(&quot;We are connected to the %s database&quot;, Dbdriver)
          }
      }
  
      if Dbdriver == &quot;postgres&quot; {
          DBURL := fmt.Sprintf(&quot;host=%s port=%s user=%s dbname=%s sslmode=disable password=%s&quot;, DbHost, DbPort, DbUser, DbName, DbPassword)
          server.DB, err = gorm.Open(Dbdriver, DBURL)
          if err != nil {
              fmt.Printf(&quot;Cannot connect to %s database&quot;, Dbdriver)
              log.Fatal(&quot;This is the error:&quot;, err)
          } else {
              fmt.Printf(&quot;We are connected to the %s database&quot;, Dbdriver)
          }
      }
  
      server.DB.Debug().AutoMigrate(&amp;users.User{}) //database migration
      server.Router = gin.Default()
  }
  
  func (server *Sever) Run(addr string) {
      fmt.Println(&quot;Listening to port 8080&quot;)
      log.Fatal(http.ListenAndServe(addr, server.Router))
  }
  </code></pre>
  <p><strong>UserDto.go</strong></p>
  <pre><code>package users
  
  import (
      &quot;strings&quot;
  
      &quot;github.com/AdieOlami/bookstore_users-api/domain/base&quot;
      &quot;github.com/AdieOlami/bookstore_users-api/utils/errors&quot;
      &quot;github.com/jinzhu/gorm&quot;
      uuid &quot;github.com/satori/go.uuid&quot;
  )
  
  type User struct {
      base.Base
      UserID    uuid.UUID `gorm:&quot;type:uuid;column:userId;not null;&quot; json:&quot;userId&quot;`
      FirstName string    `gorm:&quot;size:255;not null;unique;column:firstName&quot; json:&quot;firstName&quot;`
      LastName  string    `gorm:&quot;size:255;not null;unique;column:lastName&quot; json:&quot;lastName&quot;`
      Email     string    `gorm:&quot;size:100;not null;unique;column:email&quot; json:&quot;email&quot;`
  }
  
  func (user *User) Validate() *errors.Error {
      user.Email = strings.TrimSpace(strings.ToLower(user.Email))
      if user.Email == &quot;&quot; {
          return errors.NewBadRequestError(&quot;invalid email address&quot;)
      }
      return nil
  }
  
  func (user *User) SaveUser(db *gorm.DB) *errors.Error {
  
      var err error
      err = db.Debug().Create(&amp;user).Error
      if err != nil {
          return errors.NewInteralServerError(err.Error())
      }
      return nil
  }
  </code></pre>
  <p><strong>UserService.go</strong></p>
  <pre><code>package services
  
  import (
  
      &quot;github.com/AdieOlami/bookstore_users-api/domain/users&quot;
      &quot;github.com/AdieOlami/bookstore_users-api/utils/errors&quot;
  )
  
  func (server *Server) CreateUser(user users.User) (*users.User, *errors.Error) {
  
      if err := user.Validate(); err != nil {
          return nil, err
      }
  
      if err := user.SaveUser(server.DB); err != nil {
          return nil, err
      }
      return &amp;user, nil
  }
  </code></pre>
  <p><strong>UserController.go</strong></p>
  <pre><code>package users
  
  import (
      &quot;net/http&quot;
      &quot;strconv&quot;
  
      &quot;github.com/AdieOlami/bookstore_users-api/domain/users&quot;
      &quot;github.com/AdieOlami/bookstore_users-api/services&quot;
      &quot;github.com/AdieOlami/bookstore_users-api/utils/errors&quot;
      &quot;github.com/gin-gonic/gin&quot;
  )
  
  var (
      server = services.Server{}
  )
  
  // CREATE USER
  func CreateUser(c *gin.Context) {
      var user users.User
  
      if err := c.ShouldBindJSON(&amp;user); err != nil {
          // TODO: hnadle json error return bad request
          err := errors.NewBadRequestError(&quot;invalid json body&quot;)
          c.JSON(err.Status, err)
          // fmt.Println(err.Error())
          return
      }
      result, saveErr := server.CreateUser(user)
      if saveErr != nil {
          // TODO: handle user createing error
          c.JSON(saveErr.Status, saveErr)
          return
      }
      c.JSON(http.StatusCreated, result)
  }
  </code></pre>
  <p><strong>Routes.go</strong></p>
  <pre><code>package app
  
  import (
      &quot;github.com/AdieOlami/bookstore_users-api/controllers/users&quot;
      &quot;github.com/AdieOlami/bookstore_users-api/database/postgres&quot;
  )
  
  var (
      server = postgres.Sever{}
  )
  
  func initializeRoutes() {
  
      server.Router.POST(&quot;/users&quot;, users.CreateUser)
  }
  </code></pre>
  <p><strong>Application.go</strong></p>
  <pre><code>package app
  
  import (
      &quot;os&quot;
  
      &quot;github.com/AdieOlami/bookstore_users-api/seed&quot;
  
      _ &quot;github.com/jinzhu/gorm/dialects/mysql&quot;    //mysql database driver
      _ &quot;github.com/jinzhu/gorm/dialects/postgres&quot; //postgres database driver
  )
  
  func StartApplication() {
  
      server.Initialize(os.Getenv(&quot;DB_DRIVER&quot;), os.Getenv(&quot;DB_USER&quot;), os.Getenv(&quot;DB_PASSWORD&quot;), os.Getenv(&quot;DB_PORT&quot;), os.Getenv(&quot;DB_HOST&quot;), os.Getenv(&quot;DB_NAME&quot;))
  
      seed.Load(server.DB)
      server.Run(&quot;:8088&quot;)
      initializeRoutes()
  }
  </code></pre>
  <p>in my <strong>Main.go</strong></p>
  <pre><code>func main() {
      app.StartApplication()
  }
  </code></pre>