Go·接收POST请求
package main //接收Post请求 import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" ) func main() { //解决静态文件访问 404 ,通过/upload/文件夹./upload里的内容 http.Handle("/upload/", http.FileServer(http.Dir("./upload"))) //访问服务器目录./public文件夹里的内容,可以通过 http://localhost:3000/static来进行访问。 //http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./upload")))) http.HandleFunc("/PostJson", PostJson) //application/json 请求 http.HandleFunc("/handlePostForm", handlePostForm) //application/x-www-form-urlencoded 请求 log.Println("运行了 9999端口") err := http.ListenAndServe(":9999", nil) //监听端口 if err != nil { log.Fatal("ListenAndServe: ", err.Error()) } } //AutoGenerated 结构体 type AutoGenerated struct { Aa string `json:"aa"` Bb string `json:"bb"` Cc struct { Dd string `json:"dd"` } `json:"Cc"` //首字母大写,两边一一对应 变量名 } //接收 application/json 请求 func PostJson(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { log.Println(err) } log.Printf("%s", body) //打印接收结果 var data AutoGenerated json.Unmarshal([]byte(body), &data) //Json结构返回 json, _ := json.Marshal(data) w.Write(json) } // 接收 application/x-www-form-urlencoded 请求 func handlePostForm(writer http.ResponseWriter, request *http.Request) { request.ParseForm() // 第一种方式 // username := request.Form["username"][0] // password := request.Form["password"][0] // 第二种方式 username := request.Form.Get("a") password := request.Form.Get("b") fmt.Printf("POST form-urlencoded 参数 a=%s, b=%s\n", username, password) fmt.Fprintf(writer, `{"code":1}`) }
959 Views