dtm/dtmcli/types.go
2021-08-01 11:36:09 +08:00

64 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package dtmcli
import (
"fmt"
"strings"
"github.com/go-resty/resty/v2"
"github.com/yedf/dtm/common"
)
// MustGenGid generate a new gid
func MustGenGid(server string) string {
res := common.MS{}
resp, err := common.RestyClient.R().SetResult(&res).Get(server + "/newGid")
if err != nil || res["gid"] == "" {
panic(fmt.Errorf("newGid error: %v, resp: %s", err, resp))
}
return res["gid"]
}
// IsFailure 如果err非空或者ret是http的响应且包含FAILURE那么返回true。此时认为业务调用失败
func IsFailure(res interface{}, err error) bool {
resp, ok := res.(*resty.Response)
return err != nil || ok && (strings.Contains(resp.String(), "FAILURE") || resp.IsError())
}
// PanicIfFailure 如果err非空或者ret是http的响应且包含FAILURE那么Panic。此时认为业务调用失败
func PanicIfFailure(res interface{}, err error) {
resp, ok := res.(*resty.Response)
failure := err != nil || ok && (strings.Contains(resp.String(), "FAILURE") || resp.IsError())
if failure {
panic(fmt.Errorf("dtm failure ret: %v err %v", res, err))
}
}
// CheckDtmResponse check the response of dtm, if not ok ,generate error
func CheckDtmResponse(resp *resty.Response, err error) error {
if err != nil {
return err
}
if !strings.Contains(resp.String(), "SUCCESS") || resp.IsError() {
return fmt.Errorf("dtm response failed: %s", resp.String())
}
return nil
}
// IDGenerator used to generate a branch id
type IDGenerator struct {
parentID string
branchID int
}
// NewBranchID generate a branch id
func (g *IDGenerator) NewBranchID() string {
if g.branchID >= 99 {
panic(fmt.Errorf("branch id is larger than 99"))
}
if len(g.parentID) >= 20 {
panic(fmt.Errorf("total branch id is longer than 20"))
}
g.branchID = g.branchID + 1
return g.parentID + fmt.Sprintf("%02d", g.branchID)
}