Cats萌萌
这是一个完整的示例:campaign.model.go:package modelsimport "database/sql"// Campaign Modeltype Campaign struct { CampaignId int `db:"campaign_id" json:"campaignId"` CampaignNme string `db:"campaign_nme" json:"campaignNme"` OrganizationId sql.NullInt64 `db:"organization_id" json:"organizationId"`}campaign.repository.go:package repositoriesimport ( "github.com/jmoiron/sqlx" "go-clean-arch/domain/models" "go-clean-arch/domain/repositories")type CampaignRepository struct { Db *sqlx.DB}func NewCampaignRepository(Db *sqlx.DB) repositories.CampaignRepository { return &CampaignRepository{Db}}func (cr *CampaignRepository)FindById(id string) (models.Campaign, error) { campaign := models.Campaign{} query := ` SELECT campaign_id, campaign_nme, organization_id FROM "CAMPAIGN" WHERE campaign_id = $1 ` err := cr.Db.Get(&campaign, query, id) if err != nil { return campaign, err } return campaign, nil}main.go:func main() { dbConf := database.PGDatabaseConfig{ Host: viper.GetString("SQL_HOST"), Port: viper.GetString("SQL_PORT"), User: viper.GetString("SQL_USER"), Password: viper.GetString("SQL_PASSWORD"), Dbname: viper.GetString("SQL_DB"), } db, err := database.ConnectPGDatabase(&dbConf) if err != nil { log.Fatal(err) } defer func () { if err := recover(); err != nil { fmt.Println(err) } }() //userRepository := repositories.NewUserRepository(db) //users, _ := userRepository.FindAll() //fmt.Printf("%#v", &users) campaignRepository := repositories.NewCampaignRepository(db) campaign, err := campaignRepository.FindById("102") if err != nil { panic(err) } fmt.Printf("%#v", campaign) campaignJSON, err := json.Marshal(campaign) if err != nil { panic(err) } fmt.Println(string(campaignJSON))}输出:☁ go-clean-arch [master] ⚡ go run main.gomodels.Campaign{CampaignId:102, CampaignNme:"Generic Party / Memories", OrganizationId:sql.NullInt64{Int64:0, Valid:false}}campaignJSON: {"campaignId":102,"campaignNme":"Generic Party / Memories","organizationId":{"Int64":0,"Valid":false}}