golang实现一个正经的接口

2023-10-10 01:38
文章标签 实现 接口 golang 正经

本文主要是介绍golang实现一个正经的接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用gin和gjson库打造的一个轻量级的http接口.

package mainimport ("database/sql""fmt"_ "github.com/go-sql-driver/mysql""github.com/gin-gonic/gin""net/http""strings""github.com/tidwall/gjson""crypto/md5"
)var gMysqlIp string = "127.0.0.1"
var gSqlDb *sql.DBconst (Err_GetData int = 1000      // Error:Get json data error!Err_GetUser int = 1001      // Error:User can not be empty!Err_GetTime int = 1002      // Error:Timestamp can not be empty!Err_GetToken int = 1003     // Error:Token can not be empty!Err_GetParams int = 1004    // Error:Params can not be empty!Err_TokenInvalid int = 1005 // Error:Token is invalid!Err_TimeInvalid int = 1006  // Error:Timestamp is invalied!Err_CustomerInvalid int = 2001  // Error:Customer is invalid!Err_ExistsCustomer  int = 2002  // Error:Current customer is existed!Err_GetLastCustomer int = 2003  // Error:Get current customer failed!Err_InsertCustomer int = 2004   // Error:Insert customer failed!Err_UpdateCustomer int = 2005   // Error:Update customer failed!Err_DomainInvalid int = 3001    // Error:Domain is invalid!Err_ExistsDomain int = 3002 // Error:Current domain is existed!Err_GetLastDomain int = 3003    // Error:Get current domain failed!Err_InsertDomain int = 3004 // Error:Insert domain failed!Err_UpdateDomain int = 3005 // Error:Update domain failed!Err_DeleteDomain int = 3006 // Error:Delete domain failed!
)const (CUSTOMER_EXISTED = 4000GET_CUSTOMER_FAILED = 4001CUSTOMER_NOT_EXISTED = 4002
)const (DOMAIN_EXISTED = 5000GET_DOMAIN_FAILED = 5001DOMAIN_NOT_EXISTED = 5002
)const (STR_USER = "user"STR_TM = "timestamp"STR_PARAMS = "params"STR_TOKEN = "token"STR_ID = "id"STR_NAME = "name"STR_CUSTID = "custId"STR_SRCIP = "srcIp"STR_LOGFMT = "logFmt"STR_LOGINTERVAL = "logInterval"STR_LOGWILD = "logWild"STR_TYPE = "type"STR_HTYPE = "hType"STR_LOGLEVEL = "logLevel"STR_BITRATE = "bitRate"STR_COSTPARE = "costWithParent"STR_DEL = "del"
)type CustomerInfo struct {Id   int64                 `json:"Id"`    //1Name string                `json:"Name"`  //2
}type DomainInfo struct {Id             int64        `json:"d_id"`               //1Name           string       `json:"d_dname"`            //2CustId         int64        `json:"d_cust_id"`          //3SrcIp          string       `json:"d_src_ip"`           //4LogFmt         int64        `json:"d_logfmt"`           //5LogInterval    int64        `json:"d_log_interval"`     //6LogWild        int64        `json:"d_log_wild"`         //7Type           int64        `json:"d_type"`             //8HType          int64        `json:"d_htype"`            //9LogLevel       int64        `json:"d_log_level"`        //10BitRate        int64        `json:"d_bit_rate"`         //11CostWithParent int64        `json:"d_cost_with_parent"` //12Del            int64        `json:"d_status"`           //13
}// 是否存在该客户
func ExistsCustomer(id int64) (bool, error) {sql := fmt.Sprintf("SELECT c_id FROM server_conf.customer WHERE c_id=%v;", id)fmt.Println(sql)rows, err := gSqlDb.Query(sql)if err != nil {return false, err}if !rows.Next() {return false, nil}return true, nil
}// 是否存在该域名
func ExistsDomain(id int64) (bool, error) {sql := fmt.Sprintf("SELECT d_id FROM server_conf.domain WHERE d_id=%v;", id)fmt.Println(sql)rows, err := gSqlDb.Query(sql)if err != nil {return false, err}if !rows.Next() {return false, nil}return true, nil
}// 获取客户信息
func GetLastCustomer(id int64, cm *CustomerInfo) (int, error) {sql := fmt.Sprintf("SELECT c_id, c_name FROM server_conf.customer WHERE c_id=%v;", id)fmt.Println(sql)rows, err := gSqlDb.Query(sql)if err != nil {fmt.Println("Get customer failed! [%s]", err)return GET_CUSTOMER_FAILED, err}if rows.Next() {//rows.Columns()err = rows.Scan(&cm.Id, &cm.Name)if err != nil {fmt.Println("Get customer failed! [%s]", err)return GET_CUSTOMER_FAILED, err}fmt.Println("customer =",cm.Id, cm.Name)} else {return CUSTOMER_NOT_EXISTED, nil}return CUSTOMER_EXISTED, nil
}// 获取域名信息
func GetLastDomainById(id int64, dm *DomainInfo) (int, error) {sql := fmt.Sprintf("SELECT d_id, d_dname, d_cust_id, d_src_ip, d_logfmt, d_log_interval, d_log_wild, d_type, d_htype, d_log_level, d_bit_rate, d_cost_with_parent, d_status FROM server_conf.domain WHERE d_id=%v;", id)fmt.Println(sql)rows, err := gSqlDb.Query(sql)if err != nil {fmt.Printf("Get domain failed! [%v]", err)return GET_DOMAIN_FAILED, err}if rows.Next() {err = rows.Scan(&dm.Id, &dm.Name, &dm.CustId, &dm.SrcIp, &dm.LogFmt, &dm.LogInterval, &dm.LogWild, &dm.Type,&dm.HType, &dm.LogLevel, &dm.BitRate, &dm.CostWithParent, &dm.Del)if err != nil {fmt.Printf("Get domain failed! [%v]", err)return GET_DOMAIN_FAILED, err}fmt.Println("domain =",dm.Id, dm.Name, dm.CustId, dm.SrcIp, dm.LogFmt, dm.LogInterval, dm.LogWild, dm.Type,dm.HType, dm.LogLevel, dm.BitRate, dm.CostWithParent, dm.Del)} else {return DOMAIN_NOT_EXISTED, nil}return DOMAIN_EXISTED, nil
}// 获取域名信息
func GetLastDomainByName(name string, dm *DomainInfo) (int, error) {sql := fmt.Sprintf("SELECT d_id, d_dname, d_cust_id, d_src_ip, d_logfmt, d_log_interval, d_log_wild, d_type, d_htype, d_log_level, d_bit_rate, d_cost_with_parent, d_status FROM server_conf.domain WHERE d_dname=\"%v\";", name)fmt.Println(sql)rows, err := gSqlDb.Query(sql)if err != nil {fmt.Printf("Get domain failed! [%v]", err)return GET_DOMAIN_FAILED, err}if rows.Next() {err = rows.Scan(&dm.Id, &dm.Name, &dm.CustId, &dm.SrcIp, &dm.LogFmt, &dm.LogInterval, &dm.LogWild, &dm.Type,&dm.HType, &dm.LogLevel, &dm.BitRate, &dm.CostWithParent, &dm.Del)if err != nil {fmt.Printf("Get domain failed! [%v]", err)return GET_DOMAIN_FAILED, err}fmt.Println("domain =",dm.Id, dm.Name, dm.CustId, dm.SrcIp, dm.LogFmt, dm.LogInterval, dm.LogWild, dm.Type,dm.HType, dm.LogLevel, dm.BitRate, dm.CostWithParent, dm.Del)} else {return DOMAIN_NOT_EXISTED, nil}return DOMAIN_EXISTED, nil
}// 插入客户信息
func InsertCustomer(cm *CustomerInfo) error {sql := "INSERT INTO server_conf.customer(c_id, c_name) VALUES("var values string = ""// IDif cm.Id != 0 {values += fmt.Sprintf("'%v',", cm.Id)}// Nameif cm.Name != "None" {values += fmt.Sprintf("'%v',", cm.Name)} else {return fmt.Errorf("Error:Customer Name cannot be empty!")}values = strings.TrimRight(values, ",")if values == "" {return fmt.Errorf("Error:Customer info cannot be empty!")}sql += values + fmt.Sprintf(");")fmt.Println(sql)res, err := gSqlDb.Exec(sql)if err != nil {return err}_, err = res.RowsAffected()if err != nil {return err}//if rows == 0 {//  return fmt.Errorf("Insert customer where id=[%v] failed!", cm.Id)//}return nil
}// 插入域名信息
func InsertDomain(dm *DomainInfo) error {sql := "INSERT server_conf.domain(d_id, d_dname, d_cust_id, d_src_ip, d_logfmt, d_log_interval, d_log_wild, d_type, d_htype, d_log_level, d_bit_rate, d_cost_with_parent, d_status) VALUES("var values string = ""// IDif dm.Id != 0 {values += fmt.Sprintf("'%v',", dm.Id)}// Nameif dm.Name != "None" {values += fmt.Sprintf("'%v',", dm.Name)} else {return fmt.Errorf("Error:Domain Name cannot be empty!")}// CustIdif dm.CustId != -1 {values += fmt.Sprintf("'%v',", dm.CustId)} else {return fmt.Errorf("Error:Domain CustId cannot be empty!")}// SrcIpif dm.SrcIp != "None" {values += fmt.Sprintf("'%v',", dm.SrcIp)} else {values += fmt.Sprintf("'%v',", "")}// LogFmtif dm.LogFmt != -1 {values += fmt.Sprintf("'%v',", dm.LogFmt)} else {values += fmt.Sprintf("'%v',", 0)}// LogIntervalif dm.LogInterval != -1 {values += fmt.Sprintf("'%v',", dm.LogInterval)} else {values += fmt.Sprintf("'%v',", 0)}// LogWildif dm.LogWild != -1 {values += fmt.Sprintf("'%v',", dm.LogWild)} else {values += fmt.Sprintf("'%v',", 0)}// Typeif dm.Type != -1 {values += fmt.Sprintf("'%v',", dm.Type)} else {values += fmt.Sprintf("'%v',", 0)}// HTypeif dm.HType != -1 {values += fmt.Sprintf("'%v',", dm.HType)} else {values += fmt.Sprintf("'%v',", 0)}// LogLevelif dm.LogLevel != -1 {values += fmt.Sprintf("'%v',", dm.LogLevel)} else {values += fmt.Sprintf("'%v',", 0)}// BitRateif dm.BitRate != -1 {values += fmt.Sprintf("'%v',", dm.BitRate)} else {values += fmt.Sprintf("'%v',", 0)}// CostWithParentif dm.CostWithParent != -1 {values += fmt.Sprintf("'%v',", dm.CostWithParent)} else {values += fmt.Sprintf("'%v',", 0)}// Delif dm.Del != -1 {values += fmt.Sprintf("'%v',", dm.Del)} else {values += fmt.Sprintf("'%v',", 0)}values = strings.TrimRight(values, ",")sql += values + fmt.Sprintf(");")fmt.Println(sql)res, err := gSqlDb.Exec(sql)if err != nil {return err}_, err = res.RowsAffected()if err != nil {return err}//if rows == 0 {//  return fmt.Errorf("Insert domain where id=[%v] failed!", dm.Id)//}return nil
}func GetCustomerInsertSql(cm *CustomerInfo) (string, error) {var values string = ""var sql string = "INSERT INTO server_conf.customer(c_id, c_name) VALUES("// IDif cm.Id != 0 {values += fmt.Sprintf("'%v',", cm.Id)}// Nameif cm.Name != "None" {values += fmt.Sprintf("'%v',", cm.Name)} else {return string(""), fmt.Errorf("Error:Customer Name cannot be empty!")}values = strings.TrimRight(values, ",")sql += values + fmt.Sprintf(");")return sql, nil
}func GetCustomerUpdateSql(cm *CustomerInfo) (string, error) {var values string = ""var sql string = "UPDATE server_conf.customer SET "// Nameif cm.Name != "None" {values += fmt.Sprintf("c_name='%v',", cm.Name)}values = strings.TrimRight(values, ",")sql += values + fmt.Sprintf(" WHERE c_id=%v;", cm.Id)return sql, nil
}// 更新客户信息
func UpdateCustomer(cm *CustomerInfo) error {if cm.Id == 0 {return fmt.Errorf("Error:Customer id can not be empty!")}last := &CustomerInfo{}n, err := GetLastCustomer(cm.Id, last)if err != nil {return err}var sql string = ""if n == CUSTOMER_NOT_EXISTED {sql, err = GetCustomerInsertSql(cm)if err != nil {return err}} else if n == CUSTOMER_EXISTED {sql, err = GetCustomerUpdateSql(cm)if err != nil {return err}}fmt.Println(sql)res, err := gSqlDb.Exec(sql)if err != nil {return err}_, err = res.RowsAffected()if err != nil {return err}//if rows == 0 {//  return fmt.Errorf("Update customer where id=[%v] failed! Id not existed!", cm.Id, cm.Id)//}return nil
}func GetDomainInsertSql(dm *DomainInfo) (string, error) {var values string = ""var sql string = "INSERT server_conf.domain(d_id, d_dname, d_cust_id, d_src_ip, d_logfmt, d_log_interval, d_log_wild, d_type, d_htype, d_log_level, d_bit_rate, d_cost_with_parent, d_status) VALUES("// IDif dm.Id != 0 {values += fmt.Sprintf("'%v',", dm.Id)}// Nameif dm.Name != "None" {values += fmt.Sprintf("'%v',", dm.Name)} else {return string(""), fmt.Errorf("Error:Domain Name cannot be empty!")}// CustIdif dm.CustId != -1 {values += fmt.Sprintf("'%v',", dm.CustId)} else {return string(""), fmt.Errorf("Error:Domain CustId cannot be empty!")}// SrcIpif dm.SrcIp != "None" {values += fmt.Sprintf("'%v',", dm.SrcIp)} else {values += fmt.Sprintf("'%v',", "")}// LogFmtif dm.LogFmt != -1 {values += fmt.Sprintf("'%v',", dm.LogFmt)} else {values += fmt.Sprintf("'%v',", 0)}// LogIntervalif dm.LogInterval != -1 {values += fmt.Sprintf("'%v',", dm.LogInterval)} else {values += fmt.Sprintf("'%v',", 0)}// LogWildif dm.LogWild != -1 {values += fmt.Sprintf("'%v',", dm.LogWild)} else {values += fmt.Sprintf("'%v',", 0)}// Typeif dm.Type != -1 {values += fmt.Sprintf("'%v',", dm.Type)} else {values += fmt.Sprintf("'%v',", 0)}// HTypeif dm.HType != -1 {values += fmt.Sprintf("'%v',", dm.HType)} else {values += fmt.Sprintf("'%v',", 0)}// LogLevelif dm.LogLevel != -1 {values += fmt.Sprintf("'%v',", dm.LogLevel)} else {values += fmt.Sprintf("'%v',", 0)}// BitRateif dm.BitRate != -1 {values += fmt.Sprintf("'%v',", dm.BitRate)} else {values += fmt.Sprintf("'%v',", 0)}// CostWithParentif dm.CostWithParent != -1 {values += fmt.Sprintf("'%v',", dm.CostWithParent)} else {values += fmt.Sprintf("'%v',", 0)}// Delif dm.Del != -1 {values += fmt.Sprintf("'%v',", dm.Del)} else {values += fmt.Sprintf("'%v',", 0)}values = strings.TrimRight(values, ",")if values == "" {return string(""), fmt.Errorf("Error:Domain info cannot be empty!")}sql += values + fmt.Sprintf(");")return sql, nil
}func GetDomainUpdateSql(dm *DomainInfo) (string,error) {var values string = ""var sql string = "UPDATE server_conf.domain SET "// Name//if dm.Name != "None" {//  values += fmt.Sprintf("d_dname='%v',", dm.Name)//}// CustIdif dm.CustId != -1 {values += fmt.Sprintf("d_cust_id='%v',", dm.CustId)}// SrcIpif dm.SrcIp != "None" {values += fmt.Sprintf("d_src_ip='%v',", dm.SrcIp)}// LogFmtif dm.LogFmt != -1 {values += fmt.Sprintf("d_logfmt='%v',", dm.LogFmt)}// LogIntervalif dm.LogInterval != -1 {values += fmt.Sprintf("d_log_interval='%v',", dm.LogInterval)}// LogWildif dm.LogWild != -1 {values += fmt.Sprintf("d_log_wild='%v',", dm.LogWild)}// Typeif dm.Type != -1 {values += fmt.Sprintf("d_type='%v',", dm.Type)}// HTypeif dm.HType != -1 {values += fmt.Sprintf("d_htype='%v',", dm.HType)}// LogLevelif dm.LogLevel != -1 {values += fmt.Sprintf("d_log_level='%v',", dm.LogLevel)}// BitRateif dm.BitRate != -1 {values += fmt.Sprintf("d_bit_rate='%v',", dm.BitRate)}// CostWithParentif dm.CostWithParent != -1 {values += fmt.Sprintf("d_cost_with_parent='%v',", dm.CostWithParent)}values = strings.TrimRight(values, ",")sql += values + fmt.Sprintf(" WHERE d_dname='%v';", dm.Name)return sql, nil
}func GetDomainDeleteSql(dm *DomainInfo) (string,error) {var values string = ""var sql string = "UPDATE server_conf.domain SET "// Delif dm.Del != -1 {values += fmt.Sprintf("d_status='%v',", dm.Del)}values = strings.TrimRight(values, ",")sql += values + fmt.Sprintf(" WHERE d_dname=\"%v\";", dm.Name)return sql, nil
}// 更新域名信息
func UpdateDomain(dm *DomainInfo) error {if dm.Id == 0 {return fmt.Errorf("Error:Domain id can not be empty!")}last := &DomainInfo{}n, err := GetLastDomainByName(dm.Name, last)if err != nil {return err}var sql string = ""if n == DOMAIN_NOT_EXISTED {sql, err = GetDomainInsertSql(dm)if err != nil {return err}} else if n == DOMAIN_EXISTED {sql, err = GetDomainUpdateSql(dm)if err != nil {return err}}fmt.Println(sql)res, err := gSqlDb.Exec(sql)if err != nil {return err}_, err = res.RowsAffected()if err != nil {return err}//if rows == 0 {//  return fmt.Errorf("Update domain where id=[%v] failed! Id [%v] not existed!", dm.Id, dm.Id)//}return nil
}// 删除域名信息
func DeleteDomain(dm *DomainInfo) error {var sql string = ""last := &DomainInfo{}n, err := GetLastDomainByName(dm.Name, last)if err != nil {return err}if n == DOMAIN_NOT_EXISTED {return fmt.Errorf("Get domain failed!")} else if n == DOMAIN_EXISTED {sql, err = GetDomainDeleteSql(dm)if err != nil {return err}}fmt.Println(sql)res, err := gSqlDb.Exec(sql)if err != nil {return err}_, err = res.RowsAffected()if err != nil {return err}return nil
}func UnmarCustomer(param string, cm *CustomerInfo) error {// 1value := gjson.Get(param, "Id")if value.Index != 0 {cm.Id = value.Int()} else {cm.Id = -1return fmt.Errorf("Error:Customer id can not be empty!")}// 2value = gjson.Get(param, "Name")if value.Index != 0 {cm.Name = value.String()} else {cm.Name = "None"}return nil
}func UnmarDomain(param string, dm *DomainInfo) error {// 1value := gjson.Get(param, STR_ID)if value.Index != 0 {dm.Id = value.Int()} else {dm.Id = -1return fmt.Errorf("Error:Domain id can not be empty!")}// 2value = gjson.Get(param, STR_NAME)if value.Index != 0 {dm.Name = value.String()} else {dm.Name = "None"}// 3value = gjson.Get(param, STR_CUSTID)if value.Index != 0 {dm.CustId = value.Int()} else {dm.CustId = -1}// 4value = gjson.Get(param, STR_SRCIP)if value.Index != 0 {dm.SrcIp = value.String()} else {dm.SrcIp = "None"}// 5value = gjson.Get(param, STR_LOGFMT)if value.Index != 0 {dm.LogFmt = value.Int()} else {dm.LogFmt = -1}// 6value = gjson.Get(param, STR_LOGINTERVAL)if value.Index != 0 {dm.LogInterval = value.Int()} else {dm.LogInterval = -1}// 7value = gjson.Get(param, STR_LOGWILD)if value.Index != 0 {dm.LogWild = value.Int()} else {dm.LogWild = -1}// 8value = gjson.Get(param, STR_TYPE)if value.Index != 0 {dm.Type = value.Int()} else {dm.Type = -1}// 9value = gjson.Get(param, STR_HTYPE)if value.Index != 0 {dm.HType = value.Int()} else {dm.HType = -1}// 10value = gjson.Get(param, STR_LOGLEVEL)if value.Index != 0 {dm.LogLevel = value.Int()} else {dm.LogLevel = -1}// 11value = gjson.Get(param, STR_BITRATE)if value.Index != 0 {dm.BitRate = value.Int()} else {dm.BitRate = -1}// 12value = gjson.Get(param, STR_COSTPARE)if value.Index != 0 {dm.CostWithParent = value.Int()} else {dm.CostWithParent = -1}// 13//value = gjson.Get(param, STR_DEL)//if value.Index != 0 {//  dm.Del = value.Int()//} else {//  dm.Del = -1//}return nil
}func ResponseSuccess(c *gin.Context, msg string) {c.JSON(http.StatusOK, gin.H{"status": gin.H{"code":  http.StatusOK,"message": msg,},})
}func ResponseError(c *gin.Context, code int, err error) {c.JSON(http.StatusOK, gin.H{"status": gin.H{"code":  code,"message": err.Error(),},})
}func GetToken(args string) string {var strKey string = "123456"args = args + strKeyfmt.Println(args)sum := md5.Sum([]byte(args))hexStr := fmt.Sprintf("%x", sum)return hexStr
}func ProcessInsertCustomer(c *gin.Context) {bytes, err := c.GetRawData()if err != nil {ResponseError(c, Err_GetData, err)return}data := string(bytes)var user stringvalue := gjson.Get(data, "User")if value.Index != 0 {user = value.String()} else {ResponseError(c, Err_GetUser, fmt.Errorf("Error:User can not be empty!"))return}var timestamp int64value = gjson.Get(data, "Timestamp")if value.Index != 0 {timestamp = value.Int()} else {ResponseError(c, Err_GetTime, fmt.Errorf("Error:Timestamp can not be empty!"))return}var token stringvalue = gjson.Get(data, "Token")if value.Index != 0 {token = value.String()} else {ResponseError(c, Err_GetToken, fmt.Errorf("Error:Token can not be empty!"))return}var params stringvalue = gjson.Get(data, "Params")if value.Index != 0 {params = value.String()} else {ResponseError(c, Err_GetParams, fmt.Errorf("Error:Params can not be empty!"))return}//fmt.Println(user, timestamp, params, token)args := user + fmt.Sprintf("%v",timestamp) + paramstk := GetToken(args)fmt.Println(tk, token)if tk != token {ResponseError(c, Err_TokenInvalid, fmt.Errorf("Error:Token is invalid!"))return}cmInfo := &CustomerInfo{}err = UnmarCustomer(params, cmInfo)if err != nil {ResponseError(c, Err_CustomerInvalid, err)return}exists, err := ExistsCustomer(cmInfo.Id)if err != nil {ResponseError(c, Err_GetLastCustomer, err)return}if exists {ResponseError(c, Err_ExistsCustomer, fmt.Errorf("Error:Customer Id [%v] is existed!", cmInfo.Id))return}err = InsertCustomer(cmInfo)if err != nil {ResponseError(c, Err_InsertCustomer, err)return}ResponseSuccess(c, "Insert customer success!")
}func ProcessInsertDomain(c *gin.Context) {bytes, err := c.GetRawData()if err != nil {ResponseError(c, Err_GetData, err)return}data := string(bytes)var user stringvalue := gjson.Get(data, "User")if value.Index != 0 {user = value.String()} else {ResponseError(c, Err_GetUser, fmt.Errorf("Error:User can not be empty!"))return}var timestamp int64value = gjson.Get(data, "Timestamp")if value.Index != 0 {timestamp = value.Int()} else {ResponseError(c, Err_GetTime, fmt.Errorf("Error:Timestamp can not be empty!"))return}var token stringvalue = gjson.Get(data, "Token")if value.Index != 0 {token = value.String()} else {ResponseError(c, Err_GetToken, fmt.Errorf("Error:Token can not be empty!"))return}var params stringvalue = gjson.Get(data, "Params")if value.Index != 0 {params = value.String()} else {ResponseError(c, Err_GetParams, fmt.Errorf("Error:Params can not be empty!"))return}//fmt.Println(user, timestamp, params, token)args := user + fmt.Sprintf("%v",timestamp) + paramstk := GetToken(args)if tk != token {ResponseError(c, Err_TokenInvalid, fmt.Errorf("Error:Token is invalid!"))return}dm := &DomainInfo{}err = UnmarDomain(params, dm)//err := json.Unmarshal([]byte(param), &dm)//if err != nil {//  ResponseError(c, err)//  return//}if err != nil {ResponseError(c, Err_DomainInvalid, err)return}fmt.Println("dm=", dm)exists, err := ExistsDomain(dm.Id)if err != nil {ResponseError(c, Err_GetLastDomain, err)return}if exists {ResponseError(c, Err_ExistsDomain, fmt.Errorf("Error:Domain Id [%v] is existed!", dm.Id))return}err = InsertDomain(dm)if err != nil {ResponseError(c, Err_InsertDomain, err)return}ResponseSuccess(c, "Insert domain success!")
}func ProcessUpdateCustomer(c *gin.Context) {bytes, err := c.GetRawData()if err != nil {ResponseError(c, Err_GetData, err)return}data := string(bytes)var user stringvalue := gjson.Get(data, STR_USER)if value.Index != 0 {user = value.String()} else {ResponseError(c, Err_GetUser, fmt.Errorf("Error:User can not be empty!"))return}var timestamp int64value = gjson.Get(data, STR_TM)if value.Index != 0 {timestamp = value.Int()} else {ResponseError(c, Err_GetTime, fmt.Errorf("Error:Timestamp can not be empty!"))return}var token stringvalue = gjson.Get(data, STR_TOKEN)if value.Index != 0 {token = value.String()} else {ResponseError(c, Err_GetToken, fmt.Errorf("Error:Token can not be empty!"))return}var params stringvalue = gjson.Get(data, STR_PARAMS)if value.Index != 0 {params = value.String()} else {ResponseError(c, Err_GetParams, fmt.Errorf("Error:Params can not be empty!"))return}//fmt.Println(user, timestamp, params, token)args := user + fmt.Sprintf("%v",timestamp) + paramstk := GetToken(args)fmt.Println(tk, token)if tk != strings.ToLower(token) {ResponseError(c, Err_TokenInvalid, fmt.Errorf("Error:Token is invalid!"))return}var bError bool = falsevar strErr string = ""if len(value.Array()) == 0 {bError = truestrErr = "Error:Params is invalid!"} else {for _, v := range value.Array() {cm := &CustomerInfo{}tmp := gjson.Get(v.String(), STR_ID)if tmp.Index != 0 {cm.Id = tmp.Int()} else {ResponseError(c, Err_GetParams, fmt.Errorf("Error:Customer id can not be empty!"))return}tmp = gjson.Get(v.String(), STR_NAME)if tmp.Index != 0 {cm.Name = tmp.String()} else {ResponseError(c, Err_GetParams, fmt.Errorf("Error:Customer name can not be empty!"))return}//err = UnmarCustomer(params, cm)//if err != nil {//  bError = true//  strErr += fmt.Sprintf("Id:%v, Err:%v",cm.Id, err.Error())//  continue//}err = UpdateCustomer(cm)if err != nil {bError = truestrErr += fmt.Sprintf("Id:%v, %v.", cm.Id, err.Error())continue}}}if bError {ResponseError(c, Err_UpdateCustomer, fmt.Errorf(strErr))} else {ResponseSuccess(c, "Update customer success!")}
}func ProcessUpdateDomain(c *gin.Context) {bytes, err := c.GetRawData()if err != nil {ResponseError(c, Err_GetData, err)return}data := string(bytes)var user stringvalue := gjson.Get(data, STR_USER)if value.Index != 0 {user = value.String()} else {ResponseError(c, Err_GetUser, fmt.Errorf("Error:User can not be empty!"))return}var timestamp int64value = gjson.Get(data, STR_TM)if value.Index != 0 {timestamp = value.Int()} else {ResponseError(c, Err_GetTime, fmt.Errorf("Error:Timestamp can not be empty!"))return}var token stringvalue = gjson.Get(data, STR_TOKEN)if value.Index != 0 {token = value.String()} else {ResponseError(c, Err_GetToken, fmt.Errorf("Error:Token can not be empty!"))return}var params stringvalue = gjson.Get(data, STR_PARAMS)if value.Index != 0 {params = value.String()} else {ResponseError(c, Err_GetParams, fmt.Errorf("Error:Params can not be empty!"))return}//fmt.Println(user, timestamp, params, token)args := user + fmt.Sprintf("%v",timestamp) + paramstk := GetToken(args)fmt.Println(tk, token)if tk != strings.ToLower(token) {ResponseError(c, Err_TokenInvalid, fmt.Errorf("Error:Token is invalid!"))return}var bError bool = falsevar strErr string = ""if len(value.Array()) == 0 {bError = truestrErr = "Error:Params is invalid!"} else {for _, v := range value.Array() {dm := &DomainInfo{}//err = UnmarDomain(params, dm)//if err != nil {//  ResponseError(c, Err_DomainInvalid, err)//  return//}//fmt.Println("dm=", dm)tmp := gjson.Get(v.String(), STR_ID)if tmp.Index != 0 {dm.Id = tmp.Int()} else {ResponseError(c, Err_DomainInvalid, fmt.Errorf("Error:Domain id can not empty!"))return}tmp = gjson.Get(v.String(), STR_NAME)if tmp.Index != 0 {dm.Name = tmp.String()}tmp = gjson.Get(v.String(), STR_CUSTID)if tmp.Index != 0 {dm.CustId = tmp.Int()}tmp = gjson.Get(v.String(), STR_SRCIP)if tmp.Index != 0 {dm.SrcIp = tmp.String()}tmp = gjson.Get(v.String(), STR_LOGFMT)if tmp.Index != 0 {dm.LogFmt = tmp.Int()}tmp = gjson.Get(v.String(), STR_LOGINTERVAL)if tmp.Index != 0 {dm.LogInterval = tmp.Int()}tmp = gjson.Get(v.String(), STR_LOGWILD)if tmp.Index != 0 {dm.LogWild = tmp.Int()}tmp = gjson.Get(v.String(), STR_TYPE)if tmp.Index != 0 {dm.Type = tmp.Int()}tmp = gjson.Get(v.String(), STR_HTYPE)if tmp.Index != 0 {dm.HType = tmp.Int()}tmp = gjson.Get(v.String(), STR_LOGLEVEL)if tmp.Index != 0 {dm.LogLevel = tmp.Int()}tmp = gjson.Get(v.String(), STR_BITRATE)if tmp.Index != 0 {dm.BitRate = tmp.Int()}tmp = gjson.Get(v.String(), STR_COSTPARE)if tmp.Index != 0 {dm.CostWithParent = tmp.Int()}err = UpdateDomain(dm)if err != nil {bError = truestrErr += fmt.Sprintf("Id:%v, %v.", dm.Id, err.Error())continue}}}if bError {ResponseError(c, Err_UpdateDomain, fmt.Errorf(strErr))} else {ResponseSuccess(c, "Update domain success!")}
}func ProcessDeleteDomain(c *gin.Context) {bytes, err := c.GetRawData()if err != nil {ResponseError(c, Err_GetData, err)return}data := string(bytes)var user stringvalue := gjson.Get(data, STR_USER)if value.Index != 0 {user = value.String()} else {ResponseError(c, Err_GetUser, fmt.Errorf("Error:User can not be empty!"))return}var timestamp int64value = gjson.Get(data, STR_TM)if value.Index != 0 {timestamp = value.Int()} else {ResponseError(c, Err_GetTime, fmt.Errorf("Error:Timestamp can not be empty!"))return}var token stringvalue = gjson.Get(data, STR_TOKEN)if value.Index != 0 {token = value.String()} else {ResponseError(c, Err_GetToken, fmt.Errorf("Error:Token can not be empty!"))return}var params stringvalue = gjson.Get(data, STR_PARAMS)if value.Index != 0 {params = value.String()} else {ResponseError(c, Err_GetParams, fmt.Errorf("Error:Params can not be empty!"))return}fmt.Println(user, timestamp, params, token)args := user + fmt.Sprintf("%v", timestamp) + paramstk := GetToken(args)fmt.Println(tk, token)if tk != strings.ToLower(token) {ResponseError(c, Err_TokenInvalid, fmt.Errorf("Error:Token is invalid!"))return}var bError bool = falsevar strErr string = ""if len(value.Array()) == 0 {bError = truestrErr = "Error:Params is invalid!"} else {for _, v := range value.Array() {fmt.Println(v)dm := &DomainInfo{}tmp := gjson.Get(v.String(), STR_NAME)if tmp.Index != 0 {dm.Name = tmp.String()} else {ResponseError(c, Err_GetParams, fmt.Errorf("Error:Domain Name can not be empty!"))return}tmp = gjson.Get(v.String(), STR_DEL)if tmp.Index != 0 {dm.Del = tmp.Int()} else {ResponseError(c, Err_GetParams, fmt.Errorf("Error:Domain Del can not be empty!"))return}//err = UnmarDomain(params, dm)//if err != nil {//  ResponseError(c, Err_DomainInvalid, err)//  return//}//fmt.Println("dm=", dm)//err := json.Unmarshal([]byte(param), &dm)//if err != nil {//  ResponseError(c, err)//  return//}err = DeleteDomain(dm)if err != nil {bError = truestrErr += fmt.Sprintf("Id:%v, %v.",dm.Id, err.Error())continue}}}if bError {ResponseError(c, Err_DeleteDomain, fmt.Errorf(strErr))} else {ResponseSuccess(c, "Delete domain success!")}
}func init() {fmt.Println("do init")var err error// 连接mysqlmysqlConn := fmt.Sprintf("root:123456@tcp(%v:3600)/server_conf?charset=utf8", gMysqlIp)gSqlDb, err = sql.Open("mysql", mysqlConn)if err != nil {fmt.Printf("connect mysql failed! [%s]", err)return}gSqlDb.SetMaxOpenConns(5)gSqlDb.SetMaxIdleConns(2)err = gSqlDb.Ping()if err != nil {fmt.Printf("connect mysql failed! [%s]", err)return} else {fmt.Println("connect mysql ok!")}
}func main() {router := gin.Default()//router.POST("/insertCustomer", func(c *gin.Context) {//  ProcessInsertCustomer(c)//})////router.POST("/insertDomain", func(c *gin.Context) {//  ProcessInsertDomain(c)//})router.POST("/sqlApi/updateCustomer", func(c *gin.Context) {ProcessUpdateCustomer(c)})router.POST("/sqlApi/updateDomain", func(c *gin.Context) {ProcessUpdateDomain(c)})router.POST("/sqlApi/deleteDomain", func(c *gin.Context) {ProcessDeleteDomain(c)})router.Run(":65235")defer gSqlDb.Close()
}

这篇关于golang实现一个正经的接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/177010

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现

基于51单片机的自动转向修复系统的设计与实现

文章目录 前言资料获取设计介绍功能介绍设计清单具体实现截图参考文献设计获取 前言 💗博主介绍:✌全网粉丝10W+,CSDN特邀作者、博客专家、CSDN新星计划导师,一名热衷于单片机技术探索与分享的博主、专注于 精通51/STM32/MSP430/AVR等单片机设计 主要对象是咱们电子相关专业的大学生,希望您们都共创辉煌!✌💗 👇🏻 精彩专栏 推荐订阅👇🏻 单片机