gdb
根据接口定义和注释自动生成接口实现
安装
go get github.com/eatMoreApple/gdb
定义接口
//go:generate gdb -type UserService -path test.go
type UserService interface {
GetUserById(user *User, id int) error // @GET("SELECT * FROM user WHERE id = ? LIMIT 1")
FindUserByAge(users []User, age int) error // @SELECT("SELECT * FROM user WHERE id = ?")
CountUserList(id *int) error // @GET("SELECT COUNT(*) FROM user")
InsertUser(data map[string]interface{}) (sql.Result, error) // @NAMED_EXEC("INSERT INTO user (name, age) VALUES (:name, :age)")
}
type User struct{}
执行go generate
生成
package main
import (
"database/sql"
"github.com/jmoiron/sqlx"
)
type UserServiceImpl struct{ DB *sqlx.DB }
func (c *UserServiceImpl) GetUserById(user *User, id int) error {
return c.DB.Get(user, "SELECT * FROM user WHERE id = ? LIMIT 1", id)
}
func (c *UserServiceImpl) FindUserByAge(users []User, age int) error {
return c.DB.Select(users, "SELECT * FROM user WHERE id = ?", age)
}
func (c *UserServiceImpl) CountUserList(id *int) error {
return c.DB.Get(id, "SELECT COUNT(*) FROM user", )
}
func (c *UserServiceImpl) InsertUser(data map[string]interface{}) (sql.Result, error) {
return c.DB.NamedExec("INSERT INTO user (name, age) VALUES (:name, :age)", data)
}