go 接收get、post参数并返回json
程序员文章站
2024-03-23 10:53:16
...
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, ¶m)
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))
}
上一篇: go语言函数
下一篇: 02go的基本数据类型