golang 把结构体解析成param样式a=x&b=y&c=z样式

func ToParam(vx interface{})string{
    var result string
    var tagName_FieldValue  = make(map[string]string)
    var SortedArr = make([]string,0)
    var tagValueTemp string
    var valueStrTemp string

    vType :=reflect.TypeOf(vx)
    vValue :=reflect.ValueOf(vx)
    for i:=0;i"xml"))
        if tagValueTemp==""|| tagValueTemp=="xml"{
            continue
        }
        valueStrTemp = vValue.Field(i).String()
        if valueStrTemp == ""{
            continue
        }
        tagName_FieldValue[tagValueTemp] = valueStrTemp
        SortedArr=append(SortedArr,tagValueTemp)
    }
    sort.Strings(SortedArr)

    for i,v:=range SortedArr{
        if i==0 {
            result= result + v+"="+tagName_FieldValue[v]
            continue
        }
        result = result+"&"+v+"="+tagName_FieldValue[v]
    }

    return result
}

测试:

func TestVXXML_ToParam(t *testing.T) {
  data := VXXML{
    Service:"pay.test.hello",
    Version:"2.0",
    Charset:"UTF-8",
    SignType:"rsa_1_256",
    MchId:"商户号",
    OutTradeNo:"132130014914",
    Body:"哼哼测试",
  }
  t.Log(ToParam(data))
}

结果:

VXWAP_test.go:15: body=哼哼测试&charset=UTF-8&mch_id=商户号&out_trade_no=132130014914&service=pay.test.hello&sign_type=rsa_1_256&version=2.0

你可能感兴趣的:(go)