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,52 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"shellrequest.go",
"sign.go",
],
importpath = "go-common/app/admin/main/growup/dao/shell",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster: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 = [
"shellrequest_test.go",
"sign_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,242 @@
package shell
import (
"bytes"
"context"
"encoding/json"
"fmt"
"go-common/app/admin/main/growup/conf"
"go-common/library/log"
"go-common/library/net/http/blademaster"
"net/http"
)
//SignInterface set signature
type SignInterface interface {
SetSign(sign string)
SetCustomerID(customerID string)
SetSignType(signType string)
}
//OrderInfo order info
type OrderInfo struct {
Brokerage string `json:"brokerage"`
Mid int64 `json:"mid"`
ThirdCoin string `json:"thirdCoin"`
ThirdCtime string `json:"thirdCtime"`
ThirdOrderNo string `json:"thirdOrderNo"`
}
//OrderRequest shell order request
type OrderRequest struct {
CustomerID string `json:"customerId"`
ProductName string `json:"productName"`
Data []OrderInfo `json:"data"`
NotifyURL string `json:"notifyUrl"`
Rate string `json:"rate"`
SignType string `json:"signType"`
Timestamp string `json:"timestamp"`
Sign string `json:"sign,omitempty"`
}
//SetSign set sign
func (o *OrderRequest) SetSign(sign string) {
o.Sign = sign
}
//SetCustomerID set customId
func (o *OrderRequest) SetCustomerID(customerID string) {
o.CustomerID = customerID
}
//SetSignType set signtype
func (o *OrderRequest) SetSignType(signType string) {
o.SignType = signType
}
//OrderResponse shell order response
type OrderResponse struct {
Errno int `json:"errno"`
Msg string `json:"msg"`
}
const (
//CallbackStatusCreate 创建中状态
CallbackStatusCreate = "CREATE"
//CallbackStatusSuccess 成功
CallbackStatusSuccess = "SUCCESS"
//CallbackStatusFail 失败
CallbackStatusFail = "FAIL"
)
//OrderCallbackJSON MsgContent in OrderCallbackParam
type OrderCallbackJSON struct {
CustomerID string `json:"customerId"`
Status string `json:"status"`
ThirdOrderNo string `json:"thirdOrderNo"`
Mid string `json:"mid"`
Ext json.RawMessage `json:"ext"`
Timestamp string `json:"timestamp"`
SignType string `json:"signType"`
Sign string `json:"sign"`
}
//IsSuccess success
func (o *OrderCallbackJSON) IsSuccess() bool {
return o.Status == CallbackStatusSuccess
}
//IsFail fail
func (o *OrderCallbackJSON) IsFail() bool {
return o.Status == CallbackStatusFail
}
//IsCreate creating
func (o *OrderCallbackJSON) IsCreate() bool {
return o.Status == CallbackStatusCreate
}
//OrderCallbackParam call back url param
type OrderCallbackParam struct {
MsgID string `form:"msgId"`
MsgContent string `form:"msgContent"`
}
//OrderCheckRequest request
type OrderCheckRequest struct {
Sign string `json:"sign,omitempty"`
SignType string `json:"signType"`
CustomerID string `json:"customerId"`
Timestamp int64 `json:"timestamp"`
ThirdOrderNos string `json:"thirdOrderNos"`
}
//SetSign set sign
func (o *OrderCheckRequest) SetSign(sign string) {
o.Sign = sign
}
//SetCustomerID set customer id
func (o *OrderCheckRequest) SetCustomerID(customerID string) {
o.CustomerID = customerID
}
//SetSignType set sign type, always "MD5"
func (o *OrderCheckRequest) SetSignType(signType string) {
o.SignType = signType
}
//OrderStatusData call back data
type OrderStatusData struct {
ThirdOrderNo string `json:"thirdOrderNo"`
Status string `json:"status"`
Mid string `json:"mid"`
}
//IsSuccess is successful
func (o *OrderStatusData) IsSuccess() bool {
return o.Status == CallbackStatusSuccess
}
//OrderCheckResponse response
type OrderCheckResponse struct {
Errno int `json:"errno"`
Msg string `json:"msg"`
Orders []OrderStatusData `json:"data"`
}
//Client shell client
type Client struct {
conf conf.ShellConfig
CustomID string
Token string
HTTPClient *blademaster.Client
isDebug bool
}
//New client
func New(conf *conf.ShellConfig, httpClient *blademaster.Client) *Client {
return &Client{
CustomID: conf.CustomID,
Token: conf.Token,
HTTPClient: httpClient,
conf: *conf,
}
}
//SetDebug set debug
func (s *Client) SetDebug(isDebug bool) {
s.isDebug = isDebug
}
//SendOrderRequest send order rquest
func (s *Client) SendOrderRequest(ctx context.Context, req *OrderRequest) (res *OrderResponse, err error) {
var host = s.conf.PayHost
if host == "" {
host = "pay.bilibili.co"
}
var url = "http://" + host + "/bk-int/brokerage/rechargeBrokerage"
res = &OrderResponse{}
err = s.SendShellRequest(ctx, url, req, res)
if err != nil {
log.Error("send order request fail, err=%s", err)
}
return
}
//SendCheckOrderRequest send check order request
func (s *Client) SendCheckOrderRequest(ctx context.Context, req *OrderCheckRequest) (res *OrderCheckResponse, err error) {
var host = s.conf.PayHost
if host == "" {
host = "pay.bilibili.co"
}
var url = "http://" + host + "/bk-int/brokerage/queryRechargeBrokerage"
res = &OrderCheckResponse{}
err = s.SendShellRequest(ctx, url, req, res)
if err != nil {
log.Error("send check order request fail, err=%s", err)
}
return
}
//SendShellRequest send request
func (s *Client) SendShellRequest(ctx context.Context, url string, req interface{}, res interface{}) (err error) {
r, ok := req.(SignInterface)
if !ok {
err = fmt.Errorf("cast fail, req is not SignInterface")
return
}
r.SetSignType("MD5")
r.SetCustomerID(s.CustomID)
sign, err := Sign(r, s.Token)
if err != nil {
return
}
r.SetSign(sign)
jsonStr, err := json.Marshal(r)
if s.isDebug {
log.Info("send request, url=%s, req=%s", url, jsonStr)
}
if err != nil {
return
}
if err != nil {
return
}
var buffer = bytes.NewBuffer(jsonStr)
httpreq, _ := http.NewRequest("POST", url, buffer)
httpreq.Header.Set("Content-Type", "application/json")
bs, err := s.HTTPClient.Raw(ctx, httpreq)
if s.isDebug {
log.Info("req=%s, response=%s", jsonStr, bs)
}
if err != nil {
log.Error("get response err, err=%s, response=%s", err, string(bs))
return
}
if err = json.Unmarshal(bs, res); err != nil {
log.Error("json decode err, response=%s", string(bs))
}
return
}

View File

@@ -0,0 +1,208 @@
package shell
import (
"context"
"flag"
"os"
"testing"
"go-common/app/admin/main/growup/conf"
"go-common/library/net/http/blademaster"
"github.com/smartystreets/goconvey/convey"
)
var (
client *Client
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "mobile.studio.growup-admin")
flag.Set("conf_token", "ac1fd397cbc33eb60541e8734844bdd5")
flag.Set("tree_id", "13583")
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/growup-admin.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
client = New(conf.Conf.ShellConf, blademaster.NewClient(conf.Conf.HTTPClient))
os.Exit(m.Run())
}
func TestShellSetSign(t *testing.T) {
convey.Convey("SetSign", t, func(ctx convey.C) {
var (
sign = "abc"
o = OrderRequest{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
o.SetSign(sign)
ctx.Convey("No return values", func(ctx convey.C) {
})
})
})
}
func TestShellSetCustomerID(t *testing.T) {
convey.Convey("SetCustomerID", t, func(ctx convey.C) {
var (
customerID = "111"
o = OrderRequest{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
o.SetCustomerID(customerID)
ctx.Convey("No return values", func(ctx convey.C) {
})
})
})
}
func TestShellSetSignType(t *testing.T) {
convey.Convey("SetSignType", t, func(ctx convey.C) {
var (
signType = "111"
o = OrderRequest{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
o.SetSignType(signType)
ctx.Convey("No return values", func(ctx convey.C) {
})
})
})
}
func TestShellIsSuccess(t *testing.T) {
convey.Convey("IsSuccess", t, func(ctx convey.C) {
var (
o = OrderCallbackJSON{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := o.IsSuccess()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestShellIsFail(t *testing.T) {
convey.Convey("IsFail", t, func(ctx convey.C) {
var (
o = OrderCallbackJSON{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := o.IsFail()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestShellIsCreate(t *testing.T) {
convey.Convey("IsCreate", t, func(ctx convey.C) {
var (
o = OrderCallbackJSON{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := o.IsCreate()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestShellNew(t *testing.T) {
convey.Convey("New", t, func(ctx convey.C) {
var (
conf = &conf.ShellConfig{}
httpClient = &blademaster.Client{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := New(conf, httpClient)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestShellSetDebug(t *testing.T) {
convey.Convey("SetDebug", t, func(ctx convey.C) {
var (
isDebug = true
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
client.SetDebug(isDebug)
ctx.Convey("No return values", func(ctx convey.C) {
})
})
})
}
func TestShellSendOrderRequest(t *testing.T) {
convey.Convey("SendOrderRequest", t, func(ctx convey.C) {
var (
c = context.Background()
req = &OrderRequest{
CustomerID: "1001",
ProductName: "test",
NotifyURL: "test",
Rate: "1",
SignType: "test",
Timestamp: "test",
Sign: "test",
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := client.SendOrderRequest(c, req)
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 TestShellSendCheckOrderRequest(t *testing.T) {
convey.Convey("SendCheckOrderRequest", t, func(ctx convey.C) {
var (
c = context.Background()
req = &OrderCheckRequest{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := client.SendCheckOrderRequest(c, req)
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 TestShellSendShellRequest(t *testing.T) {
convey.Convey("SendShellRequest", t, func(ctx convey.C) {
var (
c = context.Background()
url = "localhost:8080"
req = interface{}(0)
res = interface{}(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := client.SendShellRequest(c, url, req, res)
ctx.Convey("Then err should be not nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,264 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package shell implements calculate signature for shell(pay system) query parameters.
//
// As a simple example:
//
// type Options struct {
// Query string `json:"q"`
// ShowAll bool `json:"all"`
// Page int `json:"page,omitempty"`
// }
// use json tags
//
package shell
import (
"bytes"
"crypto/md5"
"fmt"
"io"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
)
var timeType = reflect.TypeOf(time.Time{})
//var encoderType = reflect.TypeOf(new(Encoder)).Elem()
// Encoder is an interface implemented by any type that wishes to encode
// itself into URL values in a non-standard way.
type Encoder interface {
EncodeValues(key string, v *url.Values) error
}
//Sign sign for shell request
func Sign(v interface{}, token string) (sign string, err error) {
var param string
param, err = Encode(v)
if err != nil {
return
}
var final = param + "&token=" + token
var h = md5.New()
io.WriteString(h, final)
var result = h.Sum(nil)
sign = fmt.Sprintf("%x", result)
return
}
// Encode encode with dictinary ascending order
func Encode(v interface{}) (res string, err error) {
val := reflect.ValueOf(v)
for val.Kind() == reflect.Ptr {
if val.IsNil() {
return "", nil
}
val = val.Elem()
}
if v == nil {
return "", nil
}
if val.Kind() != reflect.Struct {
return "", fmt.Errorf("query: Values() expects struct input. Got %v", val.Kind())
}
res, err = encodeValue(val, tagOptions{}, 0)
return
}
// encodeValue populates the values parameter from the struct fields in val.
// Embedded structs are followed recursively (using the rules defined in the
// Values function documentation) breadth-first.
func encodeValue(val reflect.Value, opts tagOptions, deep int) (res string, err error) {
typ := val.Type()
switch typ.Kind() {
case reflect.Struct:
return encodeStruct(val, deep+1)
case reflect.Slice, reflect.Array:
return encodeSlice(val, opts, deep+1)
default:
res = valueString(val, opts)
}
return
}
func encodeSlice(val reflect.Value, opts tagOptions, deep int) (res string, err error) {
var del byte = ','
if opts.Contains("comma") {
del = ','
} else if opts.Contains("space") {
del = ' '
} else if opts.Contains("semicolon") {
del = ';'
}
s := new(bytes.Buffer)
first := true
for i := 0; i < val.Len(); i++ {
if first {
first = false
} else {
s.WriteByte(del)
}
var r string
r, err = encodeValue(val.Index(i), opts, deep)
if err != nil {
return
}
s.WriteString(r)
}
return "[" + s.String() + "]", nil
}
func encodeStruct(val reflect.Value, deep int) (res string, err error) {
var values = make(url.Values)
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
sf := typ.Field(i)
if sf.PkgPath != "" && !sf.Anonymous { // unexported
continue
}
sv := val.Field(i)
tag := sf.Tag.Get("json")
if tag == "-" {
continue
}
name, opts := parseTag(tag)
if opts.Contains("omitempty") && isEmptyValue(sv) {
continue
}
for sv.Kind() == reflect.Ptr {
if sv.IsNil() {
break
}
sv = sv.Elem()
}
var r string
r, err = encodeValue(sv, opts, deep)
if err != nil {
return
}
values.Add(name, r)
}
if deep > 1 {
res = "{" + encode(values) + "}"
} else {
res = encode(values)
}
return res, nil
}
// valueString returns the string representation of a value.
func valueString(v reflect.Value, opts tagOptions) string {
for v.Kind() == reflect.Ptr {
if v.IsNil() {
return ""
}
v = v.Elem()
}
if v.Kind() == reflect.Bool && opts.Contains("int") {
if v.Bool() {
return "1"
}
return "0"
}
if v.Type() == timeType {
t := v.Interface().(time.Time)
if opts.Contains("unix") {
return strconv.FormatInt(t.Unix(), 10)
}
return t.Format(time.RFC3339)
}
return fmt.Sprint(v.Interface())
}
// tagOptions is the string following a comma in a struct field's "url" tag, or
// the empty string. It does not include the leading comma.
type tagOptions []string
// parseTag splits a struct field's url tag into its name and comma-separated
// options.
func parseTag(tag string) (string, tagOptions) {
s := strings.Split(tag, ",")
return s[0], s[1:]
}
// Contains checks whether the tagOptions contains the specified option.
func (o tagOptions) Contains(option string) bool {
for _, s := range o {
if s == option {
return true
}
}
return false
}
func encode(v url.Values) string {
if v == nil {
return ""
}
var buf bytes.Buffer
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
vs := v[k]
prefix := escape(k) + "="
for _, v := range vs {
if buf.Len() > 0 {
buf.WriteByte('&')
}
buf.WriteString(prefix)
buf.WriteString(escape(v))
}
}
return buf.String()
}
func escape(s string) string {
return s
}
// isEmptyValue checks if a value should be considered empty for the purposes
// of omitting fields with the "omitempty" option.
func isEmptyValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
}
if v.Type() == timeType {
return v.Interface().(time.Time).IsZero()
}
return false
}

View File

@@ -0,0 +1,42 @@
package shell
import (
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSign(t *testing.T) {
convey.Convey("Sign", t, func(ctx convey.C) {
var (
v struct {
Name string
}
token = "abc"
)
v.Name = "aaa"
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := Sign(v, token)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoEncode(t *testing.T) {
convey.Convey("Encode", t, func(ctx convey.C) {
var (
v struct {
Name string
}
)
v.Name = "aaa"
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := Encode(v)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}