使用Golang開發(fā)web后臺(tái),需要接收前端傳來(lái)的參數(shù)并作出響應(yīng),那么Golang該如何接收前端的參數(shù)呢?一起來(lái)看下吧。
Golang如何接收前端的參數(shù)
1、首先,創(chuàng)建一個(gè)Golang web服務(wù)。
package main import ( "log" "fmt" "net/http" "html/template" ) // 返回靜態(tài)頁(yè)面 func handleIndex(writer http.ResponseWriter, request *http.Request) { t, _ := template.ParseFiles("index.html") t.Execute(writer, nil) } func main() { http.HandleFunc("/", handleIndex) fmt.Println("Running at port 3000 ...") err := http.ListenAndServe(":3000", nil) if err != nil { log.Fatal("ListenAndServe: ", err.Error()) } }
index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> Golang GET&POST </body> </html>
2、然后編寫前端get post請(qǐng)求,使用了axios庫(kù),請(qǐng)自行引入。
<script> axios.get('/testGet', { params: { id: 1, } }).then((response) => { console.log(response); }); // POST數(shù)據(jù) const postData = { username: 'admin', password: '123', }; axios.post('/testPostJson', postData).then((response) => { console.log(response); }); </script>
3、接著,在Golang中實(shí)現(xiàn)接收get post參數(shù)即可。
一、Golang接收前端GET請(qǐng)求的參數(shù)
// 處理GET請(qǐng)求 func handleGet(writer http.ResponseWriter, request *http.Request) { query := request.URL.Query() // 第一種方式 // id := query["id"][0] // 第二種方式 id := query.Get("id") fmt.Printf("GET: id=%sn", id) fmt.Fprintf(writer, `{"code":0}`) } func main() { // ... http.HandleFunc("/testGet", handleGet) // ... }
服務(wù)端打印如下:
GET: id=1
二、Golang接收前端POST請(qǐng)求的參數(shù)
// 引入encoding/json包 import ( // ... "encoding/json" ) // 處理application/json類型的POST請(qǐng)求 func handlePostJson(writer http.ResponseWriter, request *http.Request) { // 根據(jù)請(qǐng)求body創(chuàng)建一個(gè)json解析器實(shí)例 decoder := json.NewDecoder(request.Body) // 用于存放參數(shù)key=value數(shù)據(jù) var params map[string]string // 解析參數(shù) 存入map decoder.Decode(¶ms) fmt.Printf("POST json: username=%s, password=%sn", params["username"], params["password"]) fmt.Fprintf(writer, `{"code":0}`) } func main() { // ... http.HandleFunc("/testPostJson", handlePostJson) // ... }
服務(wù)端打印如下:
POST json: username=admin, password=123