改进 webservice 编码规范
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
}