Last active
May 1, 2023 21:19
-
-
Save CraigChilds94/3ac22f7dac7d85f4e93078e89e854cc8 to your computer and use it in GitHub Desktop.
GORM Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code shows only byte numbers, you can use
string(JsonEncode)
at line 37 to show it in correct string.