我了解如何使用大猩猩/ mux go包返回JSON,但我希望能够在开发中打印JSON,而不必将其包装到路由端点
我有以下代码,并希望列出postgresql数据库中的用户
package main
import (
"encoding/json"
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var DB *gorm.DB
var err error
const DNS = "host=localhost user=postgres_user password=postgres_password dbname=postgres_db port=5432 sslmode=disable"
type User struct {
gorm.Model
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Email string `json:"email"`
}
func PostgresTest() {
DB, err = gorm.Open(postgres.Open(DNS), &gorm.Config{})
if err != nil {
fmt.Println(err.Error())
panic("Cannot connect to DB")
}
var users []User
DB.Limit(2).Find(&users)
// json.NewEncoder(w).Encode(users)
fmt.Println(json.Marshal(users))
}
func main() {
PostgresTest()
}
这是我期待的
[
{
"ID": 1,
"CreatedAt": "2021-09-06T14:18:47.766414-05:00",
"UpdatedAt": "2021-09-06T14:18:47.766414-05:00",
"DeletedAt": null,
"firstname": "first1",
"lastname": "last1",
"email": "first1.last1@email.com"
},
{
"ID": 2,
"CreatedAt": "2021-09-06T14:18:58.144181-05:00",
"UpdatedAt": "2021-09-06T14:18:58.144181-05:00",
"DeletedAt": null,
"firstname": "first2",
"lastname": "last2",
"email": "first2.last2@email.com"
}
]
我该怎么做才能打印 JSON 或 JSON 列表?
慕容森
红糖糍粑
相关分类