Commit d2abfade authored by shajiaiming's avatar shajiaiming

托管币种

parent 6b9389d7
This diff is collapsed.
package models
import (
"bwallet/pkg/setting"
"github.com/jinzhu/gorm"
)
type TrusteeshipCoin struct {
Model
Id int `json:"primary_key,omitempty"`
Cid int `json:"cid"`
Sort int `json:"sort"`
PlatformId int `json:"platform_id"`
CoinInfo *Coin `gorm:"foreignkey:Cid" json:"coin"`
}
func (c TrusteeshipCoin) TableName() string {
return setting.DatabaseSetting.Name_Sources + ".wallet_trusteeship_coin"
}
func GetTrusteeshipCoin(id int) (*TrusteeshipCoin, error) {
var trusteeshipCoin TrusteeshipCoin
err := db.Where("id = ?", id).First(&trusteeshipCoin).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
err = db.Model(&trusteeshipCoin).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return &trusteeshipCoin, nil
}
func ExistTrusteeshipCoinById(id int) (bool, error) {
var coinRecommend TrusteeshipCoin
err := db.Select("id").Where("id = ?", id).First(&coinRecommend).Error
if err != nil && err != gorm.ErrRecordNotFound {
return false, err
}
if coinRecommend.ID > 0 {
return true, nil
}
return false, nil
}
func GetTrusteeshipCoinTotal(maps interface{}) (int, error) {
var count int
if err := db.Model(&TrusteeshipCoin{}).Where(maps).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
func GetTrusteeshipCoins(pageNum, pageSize int, maps interface{}) ([]*TrusteeshipCoin, error) {
var coinsRecommend []*TrusteeshipCoin
err := db.Preload("CoinInfo").Where(maps).Order("sort").Offset(pageNum).Limit(pageSize).Find(&coinsRecommend).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return coinsRecommend, nil
}
func AddTrusteeshipCoin(data map[string]interface{}) (error) {
coinRecommend := TrusteeshipCoin{
Cid: data["cid"].(int),
Sort: data["sort"].(int),
PlatformId: data["platform_id"].(int),
}
if err := db.Create(&coinRecommend).Error; err != nil {
return err
}
return nil
}
func EditTrusteeshipCoin(id int, data interface{}) error {
if err := db.Model(&TrusteeshipCoin{}).Where("id = ?", id).Updates(data).Error; err != nil {
return err
}
return nil
}
func DeleteTrusteeshipCoin(id int) error {
if err := db.Where("id = ?", id).Delete(TrusteeshipCoin{}).Error; err != nil {
return err
}
return nil
}
func DeleteTrusteeshipByCondition(maps interface{}) error {
if err := db.Where(maps).Delete(TrusteeshipCoin{}).Error; err != nil {
return err
}
return nil
}
package gredis
import (
"bwallet/pkg/util"
"fmt"
"github.com/gomodule/redigo/redis"
"time"
)
var (
DEFAULT = time.Duration(0) // 过期时间 不设置
FOREVER = time.Duration(-1) // 过期时间不设置
)
type Cache struct {
pool *redis.Pool
defaultExpiration time.Duration
}
// 返回cache 对象, 在多个工具之间建立一个 中间初始化的时候使用
func NewRedisCache(db int, host string, defaultExpiration time.Duration) Cache {
pool := &redis.Pool{
MaxActive: 100, // 最大连接数,即最多的tcp连接数,一般建议往大的配置,但不要超过操作系统文件句柄个数(centos下可以ulimit -n查看)
MaxIdle: 100, // 最大空闲连接数,即会有这么多个连接提前等待着,但过了超时时间也会关闭。
IdleTimeout: time.Duration(100) * time.Second, // 空闲连接超时时间,但应该设置比redis服务器超时时间短。否则服务端超时了,客户端保持着连接也没用
Wait: true, // 当超过最大连接数 是报错还是等待, true 等待 false 报错
Dial: func() (redis.Conn, error) {
conn, err := redis.Dial("tcp", host, redis.DialDatabase(db))
if err != nil {
fmt.Println(err)
return nil, err
}
return conn, nil
},
}
return Cache{pool: pool, defaultExpiration: defaultExpiration}
}
// string 类型 添加, v 可以是任意类型
func (c Cache) StringSet(name string, v interface{}) error {
conn := c.pool.Get()
s, _ := util.Serialization(v) // 序列化
defer conn.Close()
_, err := conn.Do("SET", name, s)
return err
}
// 获取 字符串类型的值
func (c Cache) StringGet(name string, v interface{}) error {
conn := c.pool.Get()
defer conn.Close()
temp, _ := redis.Bytes(conn.Do("Get", "yang"))
err := util.Deserialization(temp, &v) // 反序列化
return err
}
func (c Cache) stringGetTest() {
//var need []string
//var need int32
var need int64
//Deserialization(aa, &need)
c.StringGet("yang", &need)
}
// 判断所在的 key 是否存在
func (c Cache) Exist(name string) (bool, error) {
conn := c.pool.Get()
defer conn.Close()
v, err := redis.Bool(conn.Do("EXISTS", name))
return v, err
}
// 自增
func (c Cache) StringIncr(name string) (int, error) {
conn := c.pool.Get()
defer conn.Close()
v, err := redis.Int(conn.Do("INCR", name))
return v, err
}
// 设置过期时间 (单位 秒)
func (c Cache) Expire(name string, newSecondsLifeTime int64) error {
// 设置key 的过期时间
conn := c.pool.Get()
defer conn.Close()
_, err := conn.Do("EXPIRE", name, newSecondsLifeTime)
return err
}
// 删除指定的键
func (c Cache) Delete(keys ...interface{}) (bool, error) {
conn := c.pool.Get()
defer conn.Close()
v, err := redis.Bool(conn.Do("DEL", keys...))
return v, err
}
// 查看指定的长度
func (c Cache) StrLen(name string) (int, error) {
conn := c.pool.Get()
defer conn.Close()
v, err := redis.Int(conn.Do("STRLEN", name))
return v, err
}
// ////////////////// hash ///////////
// 删除指定的 hash 键
func (c Cache) Hdel(name, key string) (bool, error) {
conn := c.pool.Get()
defer conn.Close()
var err error
v, err := redis.Bool(conn.Do("HDEL", name, key))
return v, err
}
// 查看hash 中指定是否存在
func (c Cache) HExists(name, field string) (bool, error) {
conn := c.pool.Get()
defer conn.Close()
var err error
v, err := redis.Bool(conn.Do("HEXISTS", name, field))
return v, err
}
// 获取hash 的键的个数
func (c Cache) HLen(name string) (int, error) {
conn := c.pool.Get()
defer conn.Close()
v, err := redis.Int(conn.Do("HLEN", name))
return v, err
}
// 传入的 字段列表获得对应的值
func (c Cache) HMget(name string, fields ...string) ([]interface{}, error) {
conn := c.pool.Get()
defer conn.Close()
args := []interface{}{name}
for _, field := range fields {
args = append(args, field)
}
value, err := redis.Values(conn.Do("HMGET", args...))
return value, err
}
// 设置单个值, value 还可以是一个 map slice 等
func (c Cache) HSet(name string, key string, value interface{}) (err error) {
conn := c.pool.Get()
defer conn.Close()
v, _ := util.Serialization(value)
_, err = conn.Do("HSET", name, key, v)
return
}
// 设置多个值 , obj 可以是指针 slice map struct
func (c Cache) HMSet(name string, obj interface{}) (err error) {
conn := c.pool.Get()
defer conn.Close()
_, err = conn.Do("HSET", redis.Args{}.Add(name).AddFlat(&obj)...)
return
}
// 获取单个hash 中的值
func (c Cache) HGet(name, field string, v interface{}) (err error) {
conn := c.pool.Get()
defer conn.Close()
temp, _ := redis.Bytes(conn.Do("Get", name, field))
err = util.Deserialization(temp, &v) // 反序列化
return
}
// set 集合
// 获取 set 集合中所有的元素, 想要什么类型的自己指定
func (c Cache) Smembers(name string, v interface{}) (err error) {
conn := c.pool.Get()
defer conn.Close()
temp, _ := redis.Bytes(conn.Do("smembers", name))
err = util.Deserialization(temp, &v)
return err
}
// 获取集合中元素的个数
func (c Cache) ScardInt64s(name string) (int64, error) {
conn := c.pool.Get()
defer conn.Close()
v, err := redis.Int64(conn.Do("SCARD", name))
return v, err
}
......@@ -2,9 +2,12 @@ package util
import (
"bwallet/pkg/setting"
"encoding/json"
"errors"
"fmt"
"math"
"net"
"reflect"
"strconv"
)
......@@ -58,4 +61,52 @@ func Long2IPString(i uint) (string, error) {
ip[3] = byte(i)
return ip.String(), nil
}
\ No newline at end of file
}
func Serialization(value interface{}) ([]byte, error) {
if bytes, ok := value.([]byte); ok {
return bytes, nil
}
switch v := reflect.ValueOf(value); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return []byte(strconv.FormatInt(v.Int(), 10)), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return []byte(strconv.FormatUint(v.Uint(), 10)), nil
case reflect.Map:
}
k, err := json.Marshal(value)
return k, err
}
func Deserialization(byt []byte, ptr interface{}) (err error) {
if bytes, ok := ptr.(*[]byte); ok {
*bytes = byt
return
}
if v := reflect.ValueOf(ptr); v.Kind() == reflect.Ptr {
switch p := v.Elem(); p.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var i int64
i, err = strconv.ParseInt(string(byt), 10, 64)
if err != nil {
fmt.Printf("Deserialization: failed to parse int '%s': %s", string(byt), err)
} else {
p.SetInt(i)
}
return
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
var i uint64
i, err = strconv.ParseUint(string(byt), 10, 64)
if err != nil {
fmt.Printf("Deserialization: failed to parse uint '%s': %s", string(byt), err)
} else {
p.SetUint(i)
}
return
}
}
err = json.Unmarshal(byt, &ptr)
return
}
......@@ -10,6 +10,7 @@ import (
"bwallet/service/coin_service"
"bwallet/service/platform_chain_service"
"bwallet/service/recommend_coin_service"
"bwallet/service/trusteeship_coin_service"
"bwallet/validate_service"
"github.com/Unknwon/com"
"github.com/astaxie/beego/validation"
......@@ -307,7 +308,8 @@ func DeleteCoin(c *gin.Context) {
recommendCoinService := recommend_coin_service.RecommendCoin{Cid: id}
recommendCoinService.DeleteByCondition()
trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{Cid: id}
trusteeshipCoinService.DeleteTrusteeshipByCondition()
handler.SendResponse(c, nil, nil)
}
......
package v1
import (
"bwallet/pkg/errno"
"bwallet/pkg/handler"
"bwallet/pkg/util"
"bwallet/service/auth_service"
"bwallet/service/coin_service"
"bwallet/service/trusteeship_coin_service"
"bwallet/validate_service"
"github.com/Unknwon/com"
"github.com/astaxie/beego/validation"
"github.com/gin-gonic/gin"
"strconv"
"strings"
)
func GetTrusteeshipCoins(c *gin.Context) {
token := c.Request.Header.Get("Token")
authService := auth_service.Auth{Token: token}
auth, _ := authService.GetUserInfo()
group := auth.Group
var platform_id int
platform_id = auth.PlatformId
if ("administrator" == group) {
if arg := c.Query("platform_id"); arg != "" {
platform_id = com.StrTo(c.Query("platform_id")).MustInt()
}
}
trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{
PlatformId: platform_id,
PageNum: util.GetPage(c),
PageSize: util.GetLimit(c),
}
total, err := trusteeshipCoinService.Count()
if err != nil {
handler.SendResponse(c, errno.ErrCountCoin, nil)
return
}
coinTrusteeships, err := trusteeshipCoinService.GetAll()
if err != nil {
handler.SendResponse(c, errno.InternalServerError, nil)
return
}
data := make(map[string]interface{})
data["items"] = coinTrusteeships
data["total"] = total
handler.SendResponse(c, nil, data)
}
func AddTrusteeshipCoin(c *gin.Context) {
trusteeship_coin := validate_service.TrusteeshipCoin{}
c.ShouldBindJSON(&trusteeship_coin)
//方法一
if ok, errors := validate_service.ValidateInputs(trusteeship_coin); !ok {
for _, err := range errors {
handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
return
}
}
token := c.Request.Header.Get("Token")
authService := auth_service.Auth{Token: token}
auth, _ := authService.GetUserInfo()
group := auth.Group
var platform_id int
platform_id = auth.PlatformId
if ("administrator" == group) {
if trusteeship_coin.PlatformId != 0 {
platform_id = trusteeship_coin.PlatformId
}
}
for _, id := range strings.Split(trusteeship_coin.Cid, ",") {
if id == "" {
continue
}
coin_id, err := strconv.Atoi(id)
if (nil != err) {
continue
}
coinService := coin_service.Coin{
Id: coin_id,
}
exists, err := coinService.ExistById()
if err != nil || !exists {
continue
}
trusteeshipCoinValidate := trusteeship_coin_service.TrusteeshipCoin{
PlatformId: platform_id,
Cid: coin_id,
}
total, err := trusteeshipCoinValidate.Count()
if err != nil || total > 0 {
continue
}
trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{
Cid: coin_id,
PlatformId: platform_id,
Sort: trusteeship_coin.Sort,
}
trusteeshipCoinService.Add()
}
handler.SendResponse(c, nil, nil)
}
func EditTrusteeshipCoin(c *gin.Context) {
trusteeship_coin := validate_service.EditTrusteeshipCoin{}
c.ShouldBindJSON(&trusteeship_coin)
//方法一
if ok, errors := validate_service.ValidateInputs(trusteeship_coin); !ok {
for _, err := range errors {
handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
return
}
}
trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{
Id: trusteeship_coin.Id,
Sort: trusteeship_coin.Sort,
}
exists, err := trusteeshipCoinService.ExistById()
if err != nil {
handler.SendResponse(c, errno.ErrCoinNotFound, nil)
return
}
if !exists {
handler.SendResponse(c, errno.ErrCoinNotFound, nil)
return
}
token := c.Request.Header.Get("Token")
authService := auth_service.Auth{Token: token}
auth, _ := authService.GetUserInfo()
group := auth.Group
if ("administrator" != group) {
trusteeship_coin_model := trusteeship_coin_service.TrusteeshipCoin{Id: trusteeship_coin.Id}
trusteeship_coin, _ := trusteeship_coin_model.Get()
if trusteeship_coin.PlatformId != auth.PlatformId {
handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
return
}
}
if err := trusteeshipCoinService.Edit(); err != nil {
handler.SendResponse(c, errno.ErrUpdateCoin, nil)
return
}
handler.SendResponse(c, nil, nil)
}
func DeleteTrusteeshipCoin(c *gin.Context) {
id := com.StrTo(c.DefaultQuery("id", "0")).MustInt()
valid := validation.Validation{}
valid.Min(id, 1, "id").Message("ID必须大于0")
if valid.HasErrors() {
handler.SendResponse(c, errno.ErrValidation, nil)
return
}
trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{Id: id}
exists, err := trusteeshipCoinService.ExistById()
if err != nil {
handler.SendResponse(c, errno.ErrCoinNotFound, nil)
return
}
if !exists {
handler.SendResponse(c, errno.ErrCoinNotFound, nil)
return
}
token := c.Request.Header.Get("Token")
authService := auth_service.Auth{Token: token}
auth, _ := authService.GetUserInfo()
group := auth.Group
if ("administrator" != group) {
trusteeship_coin, _ := trusteeshipCoinService.Get()
if trusteeship_coin.PlatformId != auth.PlatformId {
handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
return
}
}
err = trusteeshipCoinService.Delete()
if err != nil {
handler.SendResponse(c, errno.ErrDeleteCoin, nil)
return
}
handler.SendResponse(c, nil, nil)
}
......@@ -72,6 +72,11 @@ func InitRouter() *gin.Engine {
api.PUT("/recommend-coin", v1.EditRecommendCoin)
api.DELETE("/recommend-coin", v1.DeleteRecommendCoin)
api.GET("/trusteeship-coins", v1.GetTrusteeshipCoins)
api.POST("/trusteeship-coin", v1.AddTrusteeshipCoin)
api.PUT("/trusteeship-coin", v1.EditTrusteeshipCoin)
api.DELETE("/trusteeship-coin", v1.DeleteTrusteeshipCoin)
api.GET("/supported-currencies", v1.GetSupportedCurrencies)
api.POST("/supported-currency", v1.AddSupportedCurrency)
api.GET("/supported-currency", v1.GetSupportedCurrency)
......
package trusteeship_coin_service
import (
"bwallet/models"
)
type TrusteeshipCoin struct {
Id int
Cid int
Sort int
PlatformId int
CategoryId uint8
PageNum int
PageSize int
}
func (c *TrusteeshipCoin) Get() (*models.TrusteeshipCoin, error) {
coinTrusteeship, err := models.GetTrusteeshipCoin(c.Id)
if err != nil {
return nil, err
}
return coinTrusteeship, nil
}
func (c *TrusteeshipCoin) GetAll() ([]*models.TrusteeshipCoin, error) {
var coinsTrusteeship []*models.TrusteeshipCoin
coinsTrusteeship, err := models.GetTrusteeshipCoins(c.PageNum, c.PageSize, c.getMaps())
if err != nil {
return nil, err
}
return coinsTrusteeship, nil
}
func (c *TrusteeshipCoin) Add() error {
coinTrusteeship := map[string]interface{}{
"cid": c.Cid,
"sort": c.Sort,
"platform_id": c.PlatformId,
}
if err := models.AddTrusteeshipCoin(coinTrusteeship); err != nil {
return err
}
return nil
}
func (c *TrusteeshipCoin) Edit() error {
return models.EditTrusteeshipCoin(c.Id, map[string]interface{}{
"sort": c.Sort,
})
}
func (c *TrusteeshipCoin) ExistById() (bool, error) {
return models.ExistTrusteeshipCoinById(c.Id)
}
func (c *TrusteeshipCoin) Count() (int, error) {
return models.GetTrusteeshipCoinTotal(c.getMaps())
}
func (c *TrusteeshipCoin) Delete() error {
return models.DeleteTrusteeshipCoin(c.Id)
}
func (c *TrusteeshipCoin) DeleteTrusteeshipByCondition() error {
return models.DeleteTrusteeshipByCondition(c.getMaps())
}
func (c *TrusteeshipCoin) getMaps() (map[string]interface{}) {
maps := make(map[string]interface{})
if c.PlatformId != 0 {
maps["platform_id"] = c.PlatformId
}
if c.Cid != 0 {
maps["cid"] = c.Cid
}
return maps
}
package validate_service
type TrusteeshipCoin struct {
Cid string `json:"cid" validate:"required"`
Sort int `json:"sort" validate:"required"`
PlatformId int `json:"platform_id" validate:"required"`
}
type EditTrusteeshipCoin struct {
Id int `json:"id" validate:"required"`
Sort int `json:"sort" validate:"required"`
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment