go 接收get、post参数并返回json

package main

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"net/http"
)

// 定义返回json结构体
type JsonResult struct {
	Errcode int
	Errmsg  string
	Result  interface{}
}

// JsonResult 设置默认值
func newJsonResult() *JsonResult {
	return &JsonResult{Errcode: 0, Errmsg: "sccess"}
}

func main() {
	http.HandleFunc("/testGet", testGet)
	http.HandleFunc("/testPost", testPost)
	http.HandleFunc("/testPostJson", testPostJson)

	err := http.ListenAndServe("127.0.0.1:8082", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

//  接受application/json类型的post请求
func testPostJson(w http.ResponseWriter, r *http.Request) {
	var param map[string]interface{}
	body, _ := ioutil.ReadAll(r.Body)
	json.Unmarshal(body, &param)

	result := make(map[string]interface{})
	result["params"] = param["username"]

	jsonResult := new(JsonResult)
	jsonResult.Errcode = 200
	jsonResult.Errmsg = "success"
	jsonResult.Result = result

	msg, _ := json.Marshal(jsonResult)

	io.WriteString(w, string(msg))
}

// 接受x-www-form-urlencoded类型的post请求
func testPost(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	// 第一种
	//name := r.Form["username"][0]
	//passwd := r.Form["passwd"][0]

	// 第二种
	name := r.Form.Get("username")
	passwd := r.Form.Get("passwd")

	result := make(map[string]string)
	result["name"] = name
	result["passwd"] = passwd

	jsonResult := new(JsonResult)
	jsonResult.Errcode = 200
	jsonResult.Errmsg = "success"
	jsonResult.Result = result

	msg, _ := json.Marshal(jsonResult)

	io.WriteString(w, string(msg))
}

// 接收get参数
func testGet(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()

	// 第一种方法
	//name := query["name"][0]

	// 第二种方法
	name := query.Get("name")

	result := make(map[string]string)
	result["name"] = name

	jsonResult := newJsonResult()

	jsonResult.Result = result

	msg, _ := json.Marshal(jsonResult)

	io.WriteString(w, string(msg))
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值