Skip to content

Instantly share code, notes, and snippets.

@CraigChilds94
Last active May 1, 2023 21:19
Show Gist options
  • Save CraigChilds94/3ac22f7dac7d85f4e93078e89e854cc8 to your computer and use it in GitHub Desktop.
Save CraigChilds94/3ac22f7dac7d85f4e93078e89e854cc8 to your computer and use it in GitHub Desktop.
GORM Example
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"encoding/json"
"fmt"
)
// The model.
type User struct {
gorm.Model
Name string `json:"name"`
}
func main() {
// Open a new connection to our sqlite database.
db, err = gorm.Open("sqlite3", "database.db")
if err != nil {
panic("Failed to open the SQLite database.")
}
// Create the table from our struct.
db.AutoMigrate(&User{})
// Create a new user in our database.
db.Create(&User{
Name: "Craig"
})
// Find all of our users.
var users []User
db.Find(&users)
// Output the users from the DB json encoded
jsonEncoded, _ := json.Marshal(&users)
fmt.Println(string(jsonEncoded))
}
@AliBigdeli0
Copy link

The code shows only byte numbers, you can use string(JsonEncode) at line 37 to show it in correct string.

@CraigChilds94
Copy link
Author

Thanks @AliBigdeli0 !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment