go语言 获取post方式json

来源:互联网 发布:mac日本官网 编辑:程序博客网 时间:2024/06/10 06:47
正在学习go语言,看了一段时间的文档,想自己写个服务器,在获取接口数据的时候发现获取数据,格式为"form-data"的数据最简单,</span>
传入post json数据:{"username":"","password":"123456"}
<span style="font-family: Arial, Helvetica, sans-serif;">req.PostForm</span>
req.Header.Get("Content-Type")req.Hostreq.Formreq.FormValue("username")req.FormValue("password")

获取"application/json"的时候,需要处理一下(以下只获取string):

package utilsimport ("bytes""io/ioutil""net/http")/**获取body的data(json)转换为string*字节数据转string*/func GetDataString(req *http.Request) string {result, err := ioutil.ReadAll(req.Body)if err != nil {return "{\"code\": 1,\"msg\": \"failed\"}"} else {return bytes.NewBuffer(result).String()}}

获取"application/json"的时候,需要处理一下(以下只获取json到map):  

需要引入的包,"io/ioutil","net/http","encoding/json"

var user map[string]interface{}body, _ := ioutil.ReadAll(req.Body)json.Unmarshal(body, &user)fmt.Println("获取json中的username:", user["username"])fmt.Println("获取json中的password:", user["password"].(string)) //转字符串通过len(password)!=0判断长度

获取的数据对比:

byte[] 

[123 34 117 115 101 114 110 97 109 101 34 58 34 115 121 115 116 101 109 34 44 34 112 97 115 115 119 111 114 100 34 58 34 49 50 51 52 53 54 34 125]
string
{"username":"system","password":"123456"}

map

map[username:system password:123456]







0 0