1 Star 0 Fork 0

xiaos/echo_demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.go 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
肖申 提交于 2018-04-08 18:11 . fc
package main
import (
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"net/http"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"errors"
"xiaos.com/echo_demo/model"
"fmt"
"reflect"
)
var DataMap = make(map[string]reflect.Type)
type sqlQuery = map[string]interface{}
type any = interface {}
func regValueType(i interface{}){
t := reflect.TypeOf(i).Elem()
DataMap[t.Name()] = t
}
func init(){
fmt.Printf("init")
regValueType(new(model.User))
}
func data_find(db *gorm.DB,query sqlQuery,result interface{}) error{
db.Debug().Where(query).Find(&result)
return nil
}
func main(){
db,err := gorm.Open("mysql","root:xs1994@/test?charset=utf8&parseTime=True&loc=Local")
if err != nil{
panic("database open error")
}
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
//save
e.POST("/data/user/:op_name", func(c echo.Context) error {
op_name := c.Param("op_name")
query := make(map[string]any)
if err := c.Bind(&query);err !=nil{
return err;
}
var rs model.User
if (op_name == "find"){
data_find(db,query,rs)
}
return c.JSON(200,rs)
})
//update
//delete
//find
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK,"hello")
})
e.POST("/user/list", func(context echo.Context) error {
users := make([]model.User,0)
db.Find(&users)
return context.JSON(200,users)
})
e.POST("/user/update", func(context echo.Context) error {
reqBody := new(model.User)
if err := context.Bind(reqBody);err!=nil{
return errors.New("bind error")
}
var user model.User
db.Debug().Model(&user).Where(sqlQuery{"id":reqBody.ID}).Update("age",reqBody.Age)
//db.Model(&user).
return context.JSON(200,user)
})
e.Logger.Fatal(e.Start(":8081"))
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lambdaxs/echo_demo.git
git@gitee.com:lambdaxs/echo_demo.git
lambdaxs
echo_demo
echo_demo
master

搜索帮助