改进 webservice 编码规范
diff --git a/message.go b/message.go
index 4036ad9..302fe6a 100644
--- a/message.go
+++ b/message.go
@@ -1,4 +1,3 @@
-// message.go
package swservice
import (
@@ -9,6 +8,7 @@
"strconv"
)
+// MessageWriter writer
type MessageWriter struct {
FuncNo int `json:"funcno"`
Attributes map[string]interface{}
@@ -18,6 +18,7 @@
Row map[string]interface{}
}
+// NewMessageReader reader
func NewMessageWriter(funcno int) *MessageWriter {
return &MessageWriter{
FuncNo: funcno,
@@ -26,9 +27,13 @@
ColumnDescs: make([]string, 0),
RowData: make([]map[string]interface{}, 0)}
}
+
+// SetAttr set attribute
func (m *MessageWriter) SetAttr(name string, value interface{}) {
m.Attributes[name] = value
}
+
+// AddCol add column data
func (m *MessageWriter) AddCol(name string, value interface{}) {
if m.Row == nil {
m.Row = make(map[string]interface{})
@@ -36,7 +41,7 @@
m.Row[name] = value
}
-func is_contains(k string, slice []string) bool {
+func isContains(k string, slice []string) bool {
for _, v := range slice {
if k == v {
return true
@@ -45,6 +50,7 @@
return false
}
+// AddRow add row
func (m *MessageWriter) AddRow() {
if m.Row == nil {
return
@@ -75,11 +81,11 @@
m.Row = nil
}
-func (m *MessageWriter) serialize_rowdata() {
+func (m *MessageWriter) serializeRowData() {
m.ColumnNames = make([]string, 0)
for _, row := range m.RowData {
for k, _ := range row {
- if !is_contains(k, m.ColumnNames) {
+ if !isContains(k, m.ColumnNames) {
m.ColumnNames = append(m.ColumnNames, k)
}
}
@@ -100,9 +106,10 @@
m.Attributes["rowcnt"] = len(rows)
}
+// Serialize 序列化
func (m *MessageWriter) Serialize() string {
m.Attributes["funcno"] = m.FuncNo
- m.serialize_rowdata()
+ m.serializeRowData()
m.Attributes["colname"] = m.ColumnNames
m.Attributes["coldesc"] = m.ColumnNames
m.Attributes["colcnt"] = len(m.ColumnNames)
@@ -111,6 +118,8 @@
}
//////////////////////////////////////////////////////////////////////
+
+// MessageReader message reader
type MessageReader struct {
FuncNo int
RetCode int
@@ -124,7 +133,7 @@
RowIndex int
}
-func get_value_as_int(value interface{}) int {
+func getValueAsInt(value interface{}) int {
// vtype := reflect.TypeOf(value)
switch value.(type) {
case int:
@@ -139,7 +148,7 @@
}
}
-func get_column_names(data interface{}) (result []string) {
+func getColumnNames(data interface{}) (result []string) {
if data == nil {
return nil
}
@@ -151,7 +160,7 @@
return
}
-func convert_to_int(value interface{}) int {
+func convertToInt(value interface{}) int {
if value == nil {
return 0
}
@@ -168,13 +177,14 @@
}
}
-func convert_to_string(value interface{}) string {
+func convertToString(value interface{}) string {
if value == nil {
return ""
}
return fmt.Sprintf("%v", value)
}
+// NewMessageReader new MessageReader
func NewMessageReader(data []byte) *MessageReader {
var s interface{}
err := json.Unmarshal(data, &s)
@@ -185,14 +195,14 @@
m := &MessageReader{Attributes: make(map[string]interface{}),
RowData: make([]map[string]interface{}, 0)}
- m.FuncNo = convert_to_int(obj["funcno"])
- m.RetCode = convert_to_int(obj["retcode"])
- m.RetMsg = convert_to_string(obj["retmsg"])
- m.DBMsg = convert_to_string(obj["dbmsg"])
- m.ErrName = convert_to_string(obj["errname"])
+ m.FuncNo = convertToInt(obj["funcno"])
+ m.RetCode = convertToInt(obj["retcode"])
+ m.RetMsg = convertToString(obj["retmsg"])
+ m.DBMsg = convertToString(obj["dbmsg"])
+ m.ErrName = convertToString(obj["errname"])
- m.ColumnNames = get_column_names(obj["colname"])
- m.ColumnDescs = get_column_names(obj["coldesc"])
+ m.ColumnNames = getColumnNames(obj["colname"])
+ m.ColumnDescs = getColumnNames(obj["coldesc"])
if rowdata, err := obj["rowdata"]; err {
if rowdata != nil {
@@ -227,14 +237,17 @@
return m
}
+// RowCount row count
func (m *MessageReader) RowCount() int {
return len(m.RowData)
}
+// HasMore has more row
func (m *MessageReader) HasMore() bool {
return m.RowIndex < m.RowCount()
}
+// NextRow next row
func (m *MessageReader) NextRow() error {
m.RowIndex++
if m.RowIndex > m.RowCount() {
@@ -243,15 +256,17 @@
return nil
}
+// GetCol get column
func (m *MessageReader) GetCol(name string) interface{} {
idx := m.RowIndex - 1
- if v, ok := m.RowData[idx][name]; !ok {
+ v, ok := m.RowData[idx][name]
+ if !ok {
return nil
- } else {
- return v
}
+ return v
}
+// GetColAsInt get column data as int
func (m *MessageReader) GetColAsInt(name string) int {
v := m.GetCol(name)
switch v.(type) {
@@ -269,11 +284,13 @@
}
}
+// GetColAsString get column data as string
func (m *MessageReader) GetColAsString(name string) string {
v := m.GetCol(name)
return fmt.Sprintf("%v", v)
}
+// GetColAsDouble get column data as double
func (m *MessageReader) GetColAsDouble(name string) float64 {
v := m.GetCol(name)
switch v.(type) {
@@ -291,10 +308,11 @@
}
}
+// GetAttr get attribute value
func (m *MessageReader) GetAttr(name string) interface{} {
- if v, ok := m.Attributes[name]; !ok {
+ v, ok := m.Attributes[name]
+ if !ok {
return nil
- } else {
- return v
}
+ return v
}
diff --git a/webservice.go b/webservice.go
index 2195a09..5e9183a 100644
--- a/webservice.go
+++ b/webservice.go
@@ -21,83 +21,100 @@
"github.com/franela/goreq"
)
+// WebSession web session object
type WebSession struct {
- AppId string
- TermId string
- Appsecret string
- BaseUrl string
+ // AppId app id
+ AppID string
+ // TermId term id
+ TermID string
+ // Appsecret secret
+ AppSecret string
+ // BaseUrl base url
+ BaseURL string
+ // DefaultTimeout default time
DefaultTimeout int
- session_key string
- ssl_verify bool
+ sessionKey string
+ sslVerify bool
httpConnectionPool sync.Pool
}
-func safe_get_json_int(value interface{}) int {
+func safeGetJSONInt(value interface{}) int {
if value == nil {
return 0
}
s := fmt.Sprintf("%v", value)
- if i, err := strconv.Atoi(s); err != nil {
+ i, err := strconv.Atoi(s)
+ if err != nil {
return 0
- } else {
- return i
}
+ return i
}
+// ServiceResponse service response object
type ServiceResponse struct {
+ // RetCode return code
RetCode int
- RetMsg string
- Result map[string]interface{}
+ // RetMsg return message
+ RetMsg string
+ // Result return data
+ Result map[string]interface{}
}
-func NewServiceResponseFromJson(json_data interface{}) *ServiceResponse {
- if json_data == nil {
+// NewServiceResponseFromJSON parse json response data
+func NewServiceResponseFromJSON(jsonData interface{}) *ServiceResponse {
+ if jsonData == nil {
return nil
}
res := &ServiceResponse{}
- res.Result = json_data.(map[string]interface{})
- res.RetCode = safe_get_json_int(res.Result["retcode"])
+ res.Result = jsonData.(map[string]interface{})
+ res.RetCode = safeGetJSONInt(res.Result["retcode"])
res.RetMsg = res.GetStrValue("retmsg")
return res
}
+
+// GetIntValue get int value
func (r *ServiceResponse) GetIntValue(name string) int {
- return safe_get_json_int(r.Result[name])
+ return safeGetJSONInt(r.Result[name])
}
+// GetStrValue get string value
func (r *ServiceResponse) GetStrValue(name string) string {
- if s, ok := r.Result[name]; ok {
+ s, ok := r.Result[name]
+ if ok {
return fmt.Sprintf("%v", s)
- } else {
- return ""
}
+ return ""
}
+// GetInterfaceValue get value as interface
func (r *ServiceResponse) GetInterfaceValue(name string) interface{} {
- if s, ok := r.Result[name]; ok {
+ s, ok := r.Result[name]
+ if ok {
return s
- } else {
- return nil
}
+ return nil
}
+
+// GetFloatValue get float value
func (r *ServiceResponse) GetFloatValue(name string) float64 {
if s, ok := r.Result[name]; ok {
t := fmt.Sprintf("%v", s)
- if f, err := strconv.ParseFloat(t, 64); err != nil {
+ f, err := strconv.ParseFloat(t, 64)
+ if err != nil {
return 0.0
- } else {
- return f
}
- } else {
- return 0.0
+ return f
}
+ return 0.0
}
+// DoGet send GET request
func (w *WebSession) DoGet(uri string, params map[string]string) (*http.Response, error) {
transport := w.httpConnectionPool.Get().(*http.Transport)
defer w.httpConnectionPool.Put(transport)
client := &http.Client{Transport: transport, Timeout: time.Duration(3) * time.Second}
- full_url := w.BaseUrl + uri
+ fullURL := w.BaseURL + uri
vl := url.Values{}
@@ -106,32 +123,36 @@
vl.Add(k, v)
}
}
- full_url = full_url + "?" + vl.Encode()
+ fullURL = fullURL + "?" + vl.Encode()
// fmt.Printf("%v\n", full_url)
- return client.Get(full_url)
+ return client.Get(fullURL)
}
+// GetTimestamp get time stamp format 20160103133455
func (w *WebSession) GetTimestamp() string {
t := time.Now()
return fmt.Sprintf("%04d%02d%02d%02d%02d%02d", t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
}
+// SignWithKey sign with key
func (w *WebSession) SignWithKey(key, message string) string {
mac := hmac.New(sha1.New, []byte(key))
mac.Write([]byte(message))
res := mac.Sum(nil)
return hex.EncodeToString(res)
}
+
+// Sign sign data
func (w *WebSession) Sign(message string) string {
- return w.SignWithKey(w.Appsecret, message)
+ return w.SignWithKey(w.AppSecret, message)
}
-func newTransport(baseurl string, ssl_verify bool) *http.Transport {
+func newTransport(baseurl string, sslVerify bool) *http.Transport {
var transport http.Transport
if strings.HasPrefix(baseurl, "https://") {
var b bool
- if ssl_verify {
+ if sslVerify {
b = false
} else {
b = true
@@ -154,23 +175,24 @@
return &transport
}
+// DoPost send POST request
func (w *WebSession) DoPost(uri string, param map[string]string) (*goreq.Response, error) {
- param["app_id"] = w.AppId
- param["term_id"] = w.TermId
+ param["app_id"] = w.AppID
+ param["term_id"] = w.TermID
param["sign_method"] = "HMAC"
- param["session_key"] = w.session_key
+ param["session_key"] = w.sessionKey
ts := w.GetTimestamp()
param["timestamp"] = ts
- param["sign"] = w.Sign(w.AppId + w.TermId + w.session_key + ts)
+ param["sign"] = w.Sign(w.AppID + w.TermID + w.sessionKey + ts)
- full_url := w.BaseUrl + uri
+ fullURL := w.BaseURL + uri
data, err := json.Marshal(param)
if err != nil {
return nil, err
}
var r *goreq.Response
r, err = goreq.Request{
- Uri: full_url,
+ Uri: fullURL,
Method: "POST",
ContentType: "application/json",
Body: data,
@@ -181,6 +203,7 @@
return r, err
}
+// Auth authorization
func (w *WebSession) Auth() error {
token, err := w.getAuthToken()
if err != nil {
@@ -193,14 +216,15 @@
return nil
}
+// NewSession new session object
func NewSession(appid, appsecret, termid, baseurl string, timeout int, sslVerify bool) *WebSession {
return &WebSession{
- AppId: appid,
- Appsecret: appsecret,
- TermId: termid,
- BaseUrl: baseurl,
+ AppID: appid,
+ AppSecret: appsecret,
+ TermID: termid,
+ BaseURL: baseurl,
DefaultTimeout: timeout,
- ssl_verify: sslVerify,
+ sslVerify: sslVerify,
httpConnectionPool: sync.Pool{New: func() interface{} {
return newTransport(baseurl, sslVerify)
}}}
@@ -208,15 +232,15 @@
func (w *WebSession) getAuthToken() (string, error) {
type FormJson struct {
- AppId string `json:"app_id"`
- TermId string `json:"term_id"`
+ AppID string `json:"app_id"`
+ TermID string `json:"term_id"`
AccessToken string `json:"access_token"`
}
- uri := fmt.Sprintf("/authservice/getauth/%v/getaccesstoken", w.AppId)
+ uri := fmt.Sprintf("/authservice/getauth/%v/getaccesstoken", w.AppID)
params := make(map[string]string)
- params["term_id"] = w.TermId
+ params["term_id"] = w.TermID
r, err := w.DoGet(uri, params)
if err != nil {
@@ -238,18 +262,19 @@
}
return s.AccessToken, nil
}
+
func (w *WebSession) getAppAccessKey(token string) error {
type FormJson struct {
- AppId string `json:"app_id"`
- TermId string `json:"term_id"`
+ AppID string `json:"app_id"`
+ TermID string `json:"term_id"`
SessionKey string `json:"session_key"`
CardKey string `json:"card_key"`
}
- uri := fmt.Sprintf("/authservice/getauth/%v", w.AppId)
+ uri := fmt.Sprintf("/authservice/getauth/%v", w.AppID)
params := make(map[string]string)
- params["term_id"] = w.TermId
+ params["term_id"] = w.TermID
params["access_token"] = token
params["timestamp"] = w.GetTimestamp()
params["v"] = "1"
@@ -277,14 +302,15 @@
log.Errorf("json unmarshal err %v", err)
return err
}
- w.session_key = s.SessionKey
+ w.sessionKey = s.SessionKey
return nil
}
+// CallYKTApi call ykt api function
func (w *WebSession) CallYKTApi(request *MessageWriter) (*MessageReader, error) {
- call_data := request.Serialize()
+ callData := request.Serialize()
params := make(map[string]string)
- params["funcdata"] = call_data
+ params["funcdata"] = callData
r, err := w.DoPost("/ecardservice/ecardapi", params)
if r != nil {
@@ -303,17 +329,19 @@
return NewMessageReader(body), nil
}
+// CallService call epay service
func (w *WebSession) CallService(path string, params map[string]interface{},
- sign_field []string, timeout int) (response *ServiceResponse, err error) {
+ signField []string, timeout int) (response *ServiceResponse, err error) {
- return w.CallService2(path, params, timeout, sign_field...)
+ return w.CallService2(path, params, timeout, signField...)
}
+// CallService2 call epay service
func (w *WebSession) CallService2(path string, params map[string]interface{}, timeout int,
- sign_field ...string) (response *ServiceResponse, err error) {
+ signField ...string) (response *ServiceResponse, err error) {
err = nil
- params["app_id"] = w.AppId
- params["term_id"] = w.TermId
+ params["app_id"] = w.AppID
+ params["term_id"] = w.TermID
ts := w.GetTimestamp()
params["timestamp"] = ts
@@ -323,17 +351,17 @@
}
sign_data := ""
- for _, k := range sign_field {
+ for _, k := range signField {
if v, ok := params[k]; ok {
sign_data += fmt.Sprintf("%v", v)
}
}
- sign_data += ts + w.session_key
+ sign_data += ts + w.sessionKey
vl.Set("sign_method", "HMAC")
- log.Debugf("Sign: key[%v] data[%v]\n", w.session_key, sign_data)
- vl.Set("sign", w.SignWithKey(w.Appsecret, sign_data))
+ log.Debugf("Sign: key[%v] data[%v]\n", w.sessionKey, sign_data)
+ vl.Set("sign", w.SignWithKey(w.AppSecret, sign_data))
- full_url := w.BaseUrl + path
+ full_url := w.BaseURL + path
log.Debugf("CallService: %v\n", full_url)
var r *goreq.Response
r, err = goreq.Request{
@@ -362,6 +390,6 @@
log.Errorf("json unmarshal err %v", err)
return
}
- response = NewServiceResponseFromJson(s)
+ response = NewServiceResponseFromJSON(s)
return
}