Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"bfs.go",
"dao.go",
"mysql.go",
],
importpath = "go-common/app/admin/main/card/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/card/conf:go_default_library",
"//app/admin/main/card/model:go_default_library",
"//library/database/orm:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"bfs_test.go",
"dao_test.go",
"mysql_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/admin/main/card/conf:go_default_library",
"//app/admin/main/card/model:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,88 @@
package dao
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"hash"
"net/http"
"strconv"
"time"
"go-common/app/admin/main/card/conf"
"go-common/library/ecode"
"go-common/library/log"
)
// bfs info
const (
_uploadURL = "/bfs/%s/%s"
_template = "%s\n%s\n%s\n%d\n"
_method = "PUT"
_bucket = "vip"
)
// Upload upload picture or log file to bfs
func (d *Dao) Upload(c context.Context, fileName string, fileType string, data []byte, bfs *conf.Bfs) (location string, err error) {
var (
req *http.Request
resp *http.Response
code int
client = &http.Client{Timeout: time.Duration(bfs.Timeout) * time.Millisecond}
url = fmt.Sprintf(bfs.Host+_uploadURL, _bucket, fileName)
)
// prepare the data of the file and init the request
buf := new(bytes.Buffer)
_, err = buf.Write(data)
if err != nil {
log.Error("Upload.buf.Write.error(%v)", err)
err = ecode.RequestErr
return
}
if req, err = http.NewRequest(_method, url, buf); err != nil {
log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
return
}
timing := time.Now().Unix()
// request setting
authorization := authorize(bfs.Key, bfs.Secret, _method, _bucket, fileName, timing)
req.Header.Set("Date", fmt.Sprint(timing))
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", fileType)
resp, err = client.Do(req)
// response treatment
if err != nil {
log.Error("Bfs client.Do(%s) error(%v)", url, err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("Bfs status code error:%v", resp.StatusCode)
return
}
code, err = strconv.Atoi(resp.Header.Get("code"))
if err != nil || code != 200 {
err = fmt.Errorf("Bfs response code error:%v", code)
return
}
location = resp.Header.Get("Location")
return
}
// authorize returns authorization for upload file to bfs
func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
var (
content string
mac hash.Hash
signature string
)
content = fmt.Sprintf(_template, method, bucket, file, expire)
mac = hmac.New(sha1.New, []byte(secret))
mac.Write([]byte(content))
signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
return
}

View File

@@ -0,0 +1,25 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoUpload(t *testing.T) {
convey.Convey("Upload", t, func(ctx convey.C) {
var (
c = context.Background()
fileName = ""
fileType = "png"
data = []byte("")
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.Upload(c, fileName, fileType, data, d.c.Bfs)
ctx.Convey("Then err should be nil.location should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,46 @@
package dao
import (
"context"
"go-common/app/admin/main/card/conf"
"go-common/library/database/orm"
"github.com/jinzhu/gorm"
)
// Dao dao
type Dao struct {
c *conf.Config
DB *gorm.DB
}
// New init mysql db
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
// db
DB: orm.NewMySQL(c.ORM),
}
d.initORM()
return
}
func (d *Dao) initORM() {
d.DB.LogMode(true)
}
// Close close the resource.
func (d *Dao) Close() {
if d.DB != nil {
d.DB.Close()
}
}
// Ping dao ping
func (d *Dao) Ping(c context.Context) (err error) {
if d.DB != nil {
err = d.DB.DB().PingContext(c)
}
return
}

View File

@@ -0,0 +1,35 @@
package dao
import (
"flag"
"os"
"testing"
"go-common/app/admin/main/card/conf"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account.card-admin")
flag.Set("conf_token", "8c94348df107609cea7a865d80fd6e23")
flag.Set("tree_id", "59197")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/card-admin.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}

View File

@@ -0,0 +1,193 @@
package dao
import (
"bytes"
"context"
"strconv"
"go-common/app/admin/main/card/model"
"go-common/library/xstr"
"github.com/pkg/errors"
)
// AddGroup add group info.
func (d *Dao) AddGroup(c context.Context, arg *model.AddGroup) error {
return d.DB.Table("card_group").Create(arg).Error
}
// UpdateGroup update group info.
func (d *Dao) UpdateGroup(c context.Context, arg *model.UpdateGroup) error {
return d.DB.Table("card_group").Where("id=?", arg.ID).Update(map[string]interface{}{
"name": arg.Name,
"state": arg.State,
"operator": arg.Operator,
}).Error
}
// Cards query cards.
func (d *Dao) Cards(c context.Context) (res []*model.Card, err error) {
err = d.DB.Table("card_info").Order("order_num desc").Where("state = 0 AND deleted = 0").Find(&res).Error
return
}
// CardsByGid query cards by group id.
func (d *Dao) CardsByGid(c context.Context, gid int64) (res []*model.Card, err error) {
err = d.DB.Table("card_info").Order("order_num desc").Where("group_id=?", gid).Where("deleted = 0").Find(&res).Error
return
}
// CardsByIds query cards by ids.
func (d *Dao) CardsByIds(c context.Context, ids []int64) (res []*model.Card, err error) {
err = d.DB.Table("card_info").Order("order_num desc").Where("id in (?)", ids).Where("deleted = 0").Find(&res).Error
return
}
// GroupsByIds query groups by ids.
func (d *Dao) GroupsByIds(c context.Context, ids []int64) (res []*model.CardGroup, err error) {
err = d.DB.Table("card_group").Order("order_num desc").Where("id in (?)", ids).Where("deleted = 0").Find(&res).Error
return
}
// AddCard add card.
func (d *Dao) AddCard(arg *model.AddCard) error {
return d.DB.Table("card_info").Create(arg).Error
}
// CardByName get card by name.
func (d *Dao) CardByName(name string) (res *model.Card, err error) {
res = new(model.Card)
q := d.DB.Table("card_info").Where("name=?", name).First(res)
if q.Error != nil {
if q.RecordNotFound() {
err = nil
res = nil
return
}
err = errors.Wrapf(err, "card by name")
}
return
}
// GroupByName get group by name.
func (d *Dao) GroupByName(name string) (res *model.CardGroup, err error) {
res = new(model.CardGroup)
q := d.DB.Table("card_group").Where("name=?", name).First(res)
if q.Error != nil {
if q.RecordNotFound() {
err = nil
res = nil
return
}
err = errors.Wrapf(err, "card_group by name")
}
return
}
// UpdateCard update card.
func (d *Dao) UpdateCard(req *model.UpdateCard) error {
args := map[string]interface{}{}
args["name"] = req.Name
args["state"] = req.State
args["is_hot"] = req.IsHot
args["operator"] = req.Operator
if req.CardURL != "" {
args["card_url"] = req.CardURL
}
if req.BigCradURL != "" {
args["big_crad_url"] = req.BigCradURL
}
return d.DB.Table("card_info").Where("id=?", req.ID).Update(args).Error
}
// UpdateCardState update card state.
func (d *Dao) UpdateCardState(c context.Context, id int64, state int8) error {
return d.DB.Table("card_info").Where("id=?", id).Update("state", state).Error
}
// DeleteCard delete card.
func (d *Dao) DeleteCard(c context.Context, id int64) error {
return d.DB.Table("card_info").Where("id=?", id).Delete(&model.Card{}).Error
}
// DeleteGroup delete group.
func (d *Dao) DeleteGroup(c context.Context, id int64) error {
return d.DB.Table("card_group").Where("id=?", id).Delete(&model.CardGroup{}).Error
}
// UpdateGroupState update group state.
func (d *Dao) UpdateGroupState(c context.Context, id int64, state int8) error {
return d.DB.Table("card_group").Where("id=?", id).Update("state", state).Error
}
// MaxCardOrder max card order num.
func (d *Dao) MaxCardOrder() (max int64, err error) {
err = d.DB.Table("card_info").Select("MAX(order_num)").Row().Scan(&max)
return
}
// MaxGroupOrder max card group order num.
func (d *Dao) MaxGroupOrder() (max int64, err error) {
err = d.DB.Table("card_group").Select("MAX(order_num)").Row().Scan(&max)
return
}
// BatchUpdateCardOrder update card order.
func (d *Dao) BatchUpdateCardOrder(c context.Context, cs []*model.Card) error {
var (
buf bytes.Buffer
ids []int64
)
buf.WriteString("UPDATE card_info SET order_num = CASE id")
for _, v := range cs {
buf.WriteString(" WHEN ")
buf.WriteString(strconv.FormatInt(v.ID, 10))
buf.WriteString(" THEN ")
buf.WriteString(strconv.FormatInt(v.OrderNum, 10))
ids = append(ids, v.ID)
}
buf.WriteString(" END WHERE id IN (")
buf.WriteString(xstr.JoinInts(ids))
buf.WriteString(");")
return d.DB.Exec(buf.String()).Error
}
// BatchUpdateCardGroupOrder update card order.
func (d *Dao) BatchUpdateCardGroupOrder(c context.Context, cs []*model.CardGroup) error {
var (
buf bytes.Buffer
ids []int64
)
buf.WriteString("UPDATE card_group SET order_num = CASE id")
for _, v := range cs {
buf.WriteString(" WHEN ")
buf.WriteString(strconv.FormatInt(v.ID, 10))
buf.WriteString(" THEN ")
buf.WriteString(strconv.FormatInt(v.OrderNum, 10))
ids = append(ids, v.ID)
}
buf.WriteString(" END WHERE id IN (")
buf.WriteString(xstr.JoinInts(ids))
buf.WriteString(");")
return d.DB.Exec(buf.String()).Error
}
// Groups query groups.
func (d *Dao) Groups(c context.Context, arg *model.ArgQueryGroup) (res []*model.CardGroup, err error) {
q := d.DB.Table("card_group").Where("deleted = 0")
if arg.GroupID > 0 {
q = q.Where("id = ?", arg.GroupID)
}
if arg.State > -1 {
q = q.Where("state = ?", arg.State)
}
if err = q.Order("order_num desc").Find(&res).Error; err != nil {
if q.RecordNotFound() {
err = nil
return
}
err = errors.Wrapf(err, "card group list")
return
}
return
}

View File

@@ -0,0 +1,311 @@
package dao
import (
"context"
"fmt"
"testing"
"time"
"go-common/app/admin/main/card/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAddGroup(t *testing.T) {
convey.Convey("AddGroup", t, func(ctx convey.C) {
var (
c = context.Background()
arg = &model.AddGroup{
Name: fmt.Sprintf("%v", time.Now().Unix()),
State: 0,
Operator: "superman",
OrderNum: time.Now().Unix(),
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddGroup(c, arg)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateGroup(t *testing.T) {
convey.Convey("UpdateGroup", t, func(ctx convey.C) {
var (
c = context.Background()
arg = &model.UpdateGroup{
ID: 1,
Name: fmt.Sprintf("%v", time.Now().UnixNano()),
State: 0,
Operator: "superman",
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.UpdateGroup(c, arg)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCards(t *testing.T) {
convey.Convey("Cards", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Cards(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGroupByName(t *testing.T) {
convey.Convey("GroupByName", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.GroupByName("te123156544664st")
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCardByName(t *testing.T) {
convey.Convey("CardByName", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.CardByName("tes...t")
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCardsByGid(t *testing.T) {
convey.Convey("CardsByGid", t, func(ctx convey.C) {
var (
c = context.Background()
gid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CardsByGid(c, gid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCardsByIds(t *testing.T) {
convey.Convey("CardsByIds", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []int64{1, 2, 3, 4, 5}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CardsByIds(c, ids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGroupsByIds(t *testing.T) {
convey.Convey("GroupsByIds", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []int64{1, 2, 3, 4, 5}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.GroupsByIds(c, ids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddCard(t *testing.T) {
convey.Convey("AddCard", t, func(ctx convey.C) {
var (
arg = &model.AddCard{
Name: fmt.Sprintf("%v", time.Now().Unix()),
State: 0,
Operator: "superman",
OrderNum: time.Now().Unix(),
CardURL: "http://www.baidu.com",
BigCradURL: "http://www.baidu.com",
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCard(arg)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateCard(t *testing.T) {
convey.Convey("UpdateCard", t, func(ctx convey.C) {
var (
req = &model.UpdateCard{
ID: 1,
Name: fmt.Sprintf("%v", time.Now().UnixNano()),
State: 0,
Operator: "superman",
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.UpdateCard(req)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateCardState(t *testing.T) {
convey.Convey("UpdateCardState", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
state = int8(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.UpdateCardState(c, id, state)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDeleteCard(t *testing.T) {
convey.Convey("DeleteCard", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DeleteCard(c, id)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDeleteGroup(t *testing.T) {
convey.Convey("DeleteGroup", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DeleteGroup(c, id)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateGroupState(t *testing.T) {
convey.Convey("UpdateGroupState", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
state = int8(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.UpdateGroupState(c, id, state)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoMaxCardOrder(t *testing.T) {
convey.Convey("MaxCardOrder", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
max, err := d.MaxCardOrder()
ctx.Convey("Then err should be nil.max should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(max, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoMaxGroupOrder(t *testing.T) {
convey.Convey("MaxGroupOrder", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
max, err := d.MaxGroupOrder()
ctx.Convey("Then err should be nil.max should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(max, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBatchUpdateCardOrder(t *testing.T) {
convey.Convey("BatchUpdateCardOrder", t, func(ctx convey.C) {
var (
c = context.Background()
cs = []*model.Card{{
ID: 1, OrderNum: 1},
{ID: 2, OrderNum: 2}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.BatchUpdateCardOrder(c, cs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoBatchUpdateCardGroupOrder(t *testing.T) {
convey.Convey("BatchUpdateCardGroupOrder", t, func(ctx convey.C) {
var (
c = context.Background()
cs = []*model.CardGroup{{ID: 2, OrderNum: 2}, {ID: 1, OrderNum: 1}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.BatchUpdateCardGroupOrder(c, cs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGroups(t *testing.T) {
convey.Convey("Groups", t, func(ctx convey.C) {
var (
c = context.Background()
arg = &model.ArgQueryGroup{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Groups(c, arg)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}