本文主要是介绍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实现一个正经的接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!