golang实现http服务端接收post请求

package main

import (
	"encoding/json"
	"log"
	"net/http"
	"time"
)

func main() {
	http.HandleFunc("/", sayHello)
	http.HandleFunc("/x",jsonReqRsp)
	s := &http.Server{
		Addr:           ":9090",
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	err := s.ListenAndServe()
	if err != nil {
		log.Fatal("listenAndServe: ", err)
	}

}

type ReqData struct{
	Opttype int `json:"opttype"`
	Data struct{
		SystemName string `json:"systemName"`
		Account []string `json:"account"`
	} `json:"data"`
}

//curl  -H "Content-Type:application/json" -X POST  -d  '{"opttype":1 ,"data": { "systemName": "systemName111", "account": ["zgx001", "ZGX00000", "ZGX00001"]} }' -i  'http://127.0.0.1:9090/x'
func jsonReqRsp(w http.ResponseWriter, r *http.Request) {
	var reqdata ReqData
	// 调用json包的解析,解析请求body
	if err:=json.NewDecoder(r.Body).Decode(&reqdata); err!=nil{
		r.Body.Close()
		log.Fatal(err)
	}
	jsonStr, _ := json.Marshal(reqdata)
	log.Println("req json: ", string(jsonStr))
	
	// 返回json字符串给客户端
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(reqdata)
}

func sayHello(w http.ResponseWriter, r *http.Request) {
	//获取post json请求转换为map
	err := r.ParseForm()
	if err != nil {
		log.Fatal("parse form error ", err)
	}
	// 初始化请求变量结构
	formData := make(map[string]interface{})
	// 调用json包的解析,解析请求body
	json.NewDecoder(r.Body).Decode(&formData)
	//log.Println("req form: ", formData)
	for key, value := range formData {
		log.Println("key:", key, " => value :", value)
	}
	// 返回json字符串给客户端
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(formData)
}

 

你可能感兴趣的:(go,go,http)