go语言 获取post方式json

正在学习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.Host
req.Form
req.FormValue("username")
req.FormValue("password")

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

package utils

import (
	"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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值