go-zero 连接 gorm 并提供 api 接口
以下是一个使用go-zero框架结合Gorm连接MySQL数据库,并提供一个简单API接口的示例。
首先,确保你已经安装了go-zero
和gorm
。
go get -u github.com/tal-tech/go-zero
go get -u gorm.io/gorm
然后,创建一个用于连接数据库的配置文件config.yaml
:
database:
host: 127.0.0.1
port: 3306
user: root
password:
name: your_database_name
定义一个模型model.go
:
package model
import (
"time"
)
type User struct {
ID int64 `gorm:"column:id"`
Name string `gorm:"column:name"`
Email string `gorm:"column:email"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
创建API服务user.go
:
package service
import (
"context"
"github.com/tal-tech/go-zero/core/stores/sqlx"
)
type UserService struct {
db *sqlx.SqlBuilder
}
func NewUserService(db *sqlx.SqlBuilder) *UserService {
return &UserService{
db: db,
}
}
func (s *UserService) GetUser(ctx context.Context, id int64) (*model.User, error) {
var user model.User
err := s.db.SelectOne(&user, "select * from user where id = ?", id)
return &user, err
}
定义API接口user.api
:
// @server(
// handler: UserHandler
// )
service user-api {
// 获取用户信息
// @handler userGet
get /users/:id (UserRequest) returns (UserResponse)
}
实现API处理逻辑userhandler.go
:
package handler
import (
"github.com/tal-tech/go-zero/rest"
"net/http"
)
func UserGetHandler(w http.ResponseWriter, r *http.Request) {
var req types.UserRequest
if err := rest.ReadRequest(w, r, &req); err != nil {
rest.Error(w, err)
return
}
user, err := logic.GetUser(r.Context(), req.Id)
if err != nil {
rest.Error(w, err)
return
}
rest.Success(w, user)
}
初始化数据库和服务main.go
:
package main
import (
"github.com/tal-tech/go-zero/core/conf"
"github.com/tal-tech/go-zero/rest"
"github.com/tal-tech/go-zero/zrpc"
)
type Config struct {
rest.RestConf
zrpc.RpcServerConf
}
func main() {
var cfg Config
conf.MustLoad("config.yaml", &cfg)
// 初始化数据库连接
sqlBuilder := sqlx.NewSqlBuilder(cfg.DataSource)
// 初始化UserService
userService := service.NewUserService(sqlBuilder)
// 初始化Rest服务
server := rest.MustNewServer(cfg.RestConf)
defer server.Stop()
// 注册UserHandler
handler.RegisterHandlers(server, userService)
// 启动服务
server.Start()
}
以上代码提供了一个简单的API服务,它连接MySQL数据库,并
评论已关闭