天天看點

go擷取post請求參數

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)
func main() {
	http.HandleFunc("/", ExampleHandler)
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

func ExampleHandler(w http.ResponseWriter, r *http.Request) {

	// 檢查是否為post請求
	if r.Method != http.MethodPost {
		w.WriteHeader(http.StatusMethodNotAllowed)
		fmt.Fprintf(w, "invalid_http_method")
		return
	}
	//application/x-www-form-urlencoded 格式
	//r.ParseForm()
	//name:=r.PostFormValue("name")
	//fmt.Fprintf(w, "x-www-form-urlencoded -> name="+name+"\n")

	//multipart/form-data 格式
	//r.ParseMultipartForm(32<<20)
	//name:=r.PostFormValue("name")
	//fmt.Fprintf(w, "multipart/form-data -> name="+name+"\n")

	//application/json格式
	defer r.Body.Close()
	con, _ := ioutil.ReadAll(r.Body) //擷取post的資料
	fmt.Fprintf(w, "application/json ->"+string(con))
}