go url 参数编码和解码

为什么80%的码农都做不了架构师?>>>   hot3.png

1

在做支付的时候会涉及到 url参数编码和解码,然后转换成自己想要的格式

app_id=2016073100129537&biz_content=%7B%22body%22%3A%22body%22%2C%22subject%22%3A%22%E5%95%86%E5%93%81%E6%A0%87%E9%A2%98%22%2C%22out_trade_no%22%3A%2201010101%22%2C%22timeout_express%22%3A%22%22%2C%22total_amount%22%3A%22100.00%22%2C%22seller_id%22%3A%22%22%2C%22product_code%22%3A%22p_1010101%22%7D&charset=utf-8&format=JSON&method=alipay.trade.app.pay¬ify_url=http%3A%2F%2F203.86.24.181%3A3000%2Falipay&sign=i0lEkNZjw%2FaBafm1HGH7wQ2KW5RWE7UUAmymwOZvbmHxofpIcGZnBBkOd%2BZolAb2XjjcPxJQ%2FrRx0Ts%2Bs58%2FpCsHR%2BOZ8jsUFX6OQweqeq4uNnugBc0bBkZBosQxLazjsn9JVnqe0IW%2BxtXzju7g7kCcXZG9l8IEgG%2BanSGpYu0%2B6Dr30f7UoZPcT3VCw%2FBNCNyh8BS0G7j%2FcCariZ3bZVLu2kUu4aHqhfzG58b2LnhAUkuZdxr6vsNZmbuC2G74yH1W9tOzBQPgKhDFagi0L3WAdL65r1wiw7RIpHVp8n41hY5YkGr%2FVbtMQoHfEtOD2kzu9%2FL8Qb2ICoBq4C9lVw%3D%3D&sign_type=RSA2×tamp=2017-11-10+17%3A54%3A34&version=1.0 
map[sign:[i0lEkNZjw/aBafm1HGH7wQ2KW5RWE7UUAmymwOZvbmHxofpIcGZnBBkOd+ZolAb2XjjcPxJQ/rRx0Ts+s58/pCsHR+OZ8jsUFX6OQweqeq4uNnugBc0bBkZBosQxLazjsn9JVnqe0IW+xtXzju7g7kCcXZG9l8IEgG+anSGpYu0+6Dr30f7UoZPcT3VCw/BNCNyh8BS0G7j/cCariZ3bZVLu2kUu4aHqhfzG58b2LnhAUkuZdxr6vsNZmbuC2G74yH1W9tOzBQPgKhDFagi0L3WAdL65r1wiw7RIpHVp8n41hY5YkGr/VbtMQoHfEtOD2kzu9/L8Qb2ICoBq4C9lVw==] app_id:[2016073100129537] format:[JSON] notify_url:[http://203.86.24.181:3000/alipay] sign_type:[RSA2] timestamp:[2017-11-10 17:54:34] version:[1.0] biz_content:[{"body":"body","subject":"商品标题","out_trade_no":"01010101","timeout_express":"","total_amount":"100.00","seller_id":"","product_code":"p_1010101"}] charset:[utf-8] method:[alipay.trade.app.pay]] 

使用

http 请求的时候将url传递的参数编码 变为 以&连接的字符串

	//构造参数
	var p = url.Values{}
	p.Add("app_id", this.appId)
	p.Add("method", param.APIName())

	//编码
	var buf io.Reader
	buf = strings.NewReader(p.Encode())
	
	//http 发送请求
	req, err := http.NewRequest(method, this.apiDomain, buf)

当需要将参数解码成url.Values{}类型,也就是 map[string][]string,使用

    //解析参数
    u, err := url.ParseQuery(result)
    fmt.Println(u, err)

2

golang中类似java的URLEncode函数的使用

Go语言的net/url包中实现了类似java URLEncoder和URLDecoder的函数,它们是

QueryEscape:类似URLEncoder

QueryUnescape:类似URLDecoder

使用例子如下:

首先要引入net/url包

import (
	"fmt"
	"net/url"
)

测试代码:

	urltest := "http://www.baidu.com/s?wd=自由度"
	fmt.Println(urltest)
	encodeurl:= url.QueryEscape(urltest)
	fmt.Println(encodeurl)
	decodeurl,err := url.QueryUnescape(encodeurl)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(decodeurl)

输出结果:

http://www.baidu.com/s?wd=自由度
http%3A%2F%2Fwww.baidu.com%2Fs%3Fwd%3D%E8%87%AA%E7%94%B1%E5%BA%A6
http://www.baidu.com/s?wd=自由度

转载于:https://my.oschina.net/solate/blog/1572926

你可能感兴趣的:(go url 参数编码和解码)