beego框架编写接口
每天花1,2个小时学习了一下go语言基础和beego框架,在公司的go语言项目写几个简单的接口(返回Json格式数据),写的比较简陋,只展示了controller层/service层/model层,还希望大家多多指教:
先看看效果(预先需要安装各种组件或拓展):bee run
postman里调试接口: http://localhost:8090/api/v1/product/products?category_id=7
ProductController.go 代码
package api
import (
"fmt"
"encoding/json"
"gitlab.com/xxxxx/xxxxx/src/v1/drivers/nblogs"
"gitlab.com/xxxxx/xxxxx/src/v1/errno"
"gitlab.com/xxxxx/xxxxx/src/v1/http/requests"
"gitlab.com/xxxxx/xxxxx/src/v1/http/resources"
"gitlab.com/xxxxx/xxxxx/src/v1/models"
"gitlab.com/xxxxx/xxxxx/src/v1/services"
)
type ProductController struct {
BaseController
}
// 获取服务项目列表
func (this *ProductController) GetProductList() {
categoryId, err := this.GetInt64("category_id") //7
if(err != nil){
nblogs.Error(err)
this.Error(errno.ErrNotFound)
}
result, err := services.GetProductList(services.Params{"category_id":categoryId}, this.AuthUser)
if(err != nil){
nblogs.Error(err)
this.Error(errno.ErrNotFound)
}
fmt.Println(result)
data := resources.NewProductCollection(result, this.AuthUser).ToArray()
this.Success(struct {
Data interface{} `json:"data"`
}{Data:data})
}
productService.go 层代码:
package services
import (
"github.com/xxxxx/beego/orm"
"gitlab.com/xxxxx/xxxxx/src/v1/drivers/nblogs"
"gitlab.com/xxxxx/xxxxx/src/v1/errno"
"gitlab.com/xxxxx/xxxxx/src/v1/helpers"
"gitlab.com/xxxxx/xxxxx/src/v1/models"
"gitlab.com/xxxxx/xxxxx/src/v1/utils/util_time"
"time"
)
type CreateProductAttributes struct {
CategoryId int64 `json:"category_id"`
Name string `json:"name"`
SubName string `json:"sub_name"`
InnerServiceTime int `json:"inner_service_time"`
Price float64 `json:"price"`
EarnestAmount float64 `json:"earnest_amount"`
}
// 获取服务项目列表
func GetProductList(params Params, user *models.User, columns ...string) (data []models.Product, err error) {
db := GetOrm()
qs := db.QueryTable(new(models.Product)).Exclude("is_deleted", 1)
if _, has := params["category_id"]; has {
categoryId := params["category_id"].(int64)
qs = qs.Filter("category_id", categoryId)
}
_, err = qs.OrderBy("sort").All(&data, columns...)
if err != nil {
nblogs.Error(err)
return
}
return
}
model/product.go model层代码:
package models
import "time"
// 服务项目模型
type Product struct {
Id int64 `json:"product_id"`
Code string `json:"code"`
CategoryId int64 `json:"category_id"`
Name string `json:"name"`
SubName string `json:"sub_name"`
LogoUrl string `json:"logo_url"`
....
}
每行的代码注释解释就不多注解了,大家可自行google
其他接口:如"修改服务项目","获取项目详情"等接口,时间关系会在后面的博客中体现,谢谢大家