package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/gorilla/mux"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"io/ioutil"
"log"
"net/http"
"time"
)
// gorm.Model 的定义
/*type Model struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}*/
type AiAlertRule struct {
//gorm.Model
Id string `sql:"id"`
UserName string `sql:"user_name"`
GroupName string `sql:"group_name"`
Role string `sql:"role"`
Editor string `sql:"editor"`
RuleName string `sql:"rule_name"`
RuleType string `sql:"rule_type"`
RuleStatus string `sql:"rule_status"`
RuleConfirm string `sql:"rule_confirm"`
Instance string `sql:"instance"`
CreatedTime time.Time `sql:"created_time"`
UpdatedTime time.Time `sql:"update_time"`
ClusterId string `sql:"clusterid"`
}
//实现 Tabler 接口来更改默认表名
type Tabler interface {
TableName() string
}
// TableName 会将 AiAlertRule 的表名重写为 `ai_alert_rule`
func (AiAlertRule) TableName() string {
return "ai_alert_rule"
}
func requestRes(writer http.ResponseWriter, request *http.Request) {
//连接数据库
dsn := "root:root@tcp(10.166.15.26:3306)/test26?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err !=nil {
fmt.Println("connect false")
}
fmt.Println(db)
fmt.Println(err)
//var aar AiAlertRule
var aars []AiAlertRule
// 获取第一条记录(主键升序)- 表名 ai_alert_rule
// SELECT * FROM ai_alert_rule ORDER BY id LIMIT 1;
//db.First(&aar)
//查询全部
result := db.Find(&aars)
fmt.Println(aars)
fmt.Println(result.RowsAffected) // 返回找到的记录数
fmt.Println(result.Error) // returns error or nil
// 检查 ErrRecordNotFound 错误
errors.Is(result.Error, gorm.ErrRecordNotFound)
//获取请求数据request
var req map[string]interface{}
body, _ := ioutil.ReadAll(request.Body)
//解码函数
//解析json编码的数据并将结果存入req指向的值
json.Unmarshal(body, &req)
//fmt.Println(req)
//var name string = req["name"].(string)
RuleName := req["RuleName"].(string)
//fmt.Println(ruleName)
//数据响应response
//var res map[string]string = map[string]string{"code": "1", "message": "ok", "body":"hello,world!"}
var res = map[string]string{"code": "1", "message": "ok", "body":"hello,world!"}
if RuleName == "" {
res = map[string]string{ "message":"RuleName null input"}
}
//fmt.Println(res)
//编码函数
response, _ := json.Marshal(res)
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
writer.Write(response)
}
func main() {
//方式二:使用mux框架
//var r *mux.Router = mux.NewRouter()
r := mux.NewRouter()
r.HandleFunc("/v1/rule/get_rule", requestRes).Methods("POST")
log.Fatal(http.ListenAndServe(":9090", r))
}
notes:
1.结构体的变量名需要大写,要不然权限访问不到
2.结构体名与数据库表名的对应,变量名与表的字段名的对应
3.输入是否为空的校验