66package main
77
88import (
9+ "encoding/json"
910 "fmt"
1011
1112 "go.osspkg.com/logx"
1213
14+ "go.osspkg.com/goppy/v2/orm/clients/sqlite"
15+
1316 "go.osspkg.com/goppy/v2"
1417 "go.osspkg.com/goppy/v2/orm"
1518 "go.osspkg.com/goppy/v2/plugins"
@@ -21,24 +24,30 @@ func main() {
2124 app := goppy .New ("goppy_database" , "v1.0.0" , "" )
2225 app .Plugins (
2326 web .WithServer (),
24- orm .WithMysqlClient (),
25- orm .WithSqliteClient (),
26- orm .WithPgsqlClient (),
27- orm .WithORM (),
27+ orm .WithORM (sqlite .Name ),
2828 orm .WithMigration (orm.Migration {
29- Tags : []string {"mysql_master " },
29+ Tags : []string {"sqlite_master " },
3030 Dialect : "mysql" ,
3131 Data : map [string ]string {
32- "0001_data.sql" : "CREATE TABLE IF NOT EXISTS `demo` (\n `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY\n );" ,
32+ "0002_data.sql" : `
33+ CREATE TABLE IF NOT EXISTS "demo2"
34+ (
35+ "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT
36+ );
37+ ` ,
3338 },
3439 }),
3540 orm .WithMigration (),
3641 )
3742 app .Plugins (
38- plugins.Plugin {
43+ plugins.Kind {
3944 Inject : NewController ,
40- Resolve : func (routes web.RouterPool , c * Controller ) {
41- router := routes .Main ()
45+ Resolve : func (routes web.ServerPool , c * Controller ) {
46+ router , ok := routes .Main ()
47+ if ! ok {
48+ return
49+ }
50+
4251 router .Use (web .ThrottlingMiddleware (100 ))
4352 router .Get ("/users" , c .Users )
4453
@@ -61,27 +70,29 @@ func NewController(orm orm.ORM) *Controller {
6170 }
6271}
6372
64- func (v * Controller ) Users (ctx web.Context ) {
65- data := []int64 {1 , 2 , 3 , 4 }
73+ func (v * Controller ) Users (ctx web.Ctx ) {
74+ data := Model { data : []int64 {1 , 2 , 3 , 4 } }
6675 ctx .JSON (200 , data )
6776}
6877
69- func (v * Controller ) User (ctx web.Context ) {
78+ func (v * Controller ) User (ctx web.Ctx ) {
7079 id , _ := ctx .Param ("id" ).Int () // nolint: errcheck
7180
72- err := v .orm .Tag ("mysql_master" ).PingContext (ctx .Context ())
73- if err != nil {
74- ctx .ErrorJSON (500 , err , web.ErrCtx {"id" : id })
75- return
76- }
77-
78- err = v .orm .Tag ("sqlite_master" ).PingContext (ctx .Context ())
81+ err := v .orm .Tag ("sqlite_master" ).PingContext (ctx .Context ())
7982 if err != nil {
80- ctx .ErrorJSON (500 , err , web. ErrCtx { "id" : id } )
83+ ctx .ErrorJSON (500 , err , "id" , id )
8184 return
8285 }
8386
84- ctx .ErrorJSON (400 , fmt .Errorf ("user not found" ), web. ErrCtx { "id" : id } )
87+ ctx .ErrorJSON (200 , fmt .Errorf ("user not found" ), "id" , id )
8588
8689 logx .Info ("user" , "id" , id )
8790}
91+
92+ type Model struct {
93+ data []int64
94+ }
95+
96+ func (m Model ) MarshalJSON () ([]byte , error ) {
97+ return json .Marshal (m .data )
98+ }
0 commit comments