新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
Golang怎么接收前端的參數(shù)-創(chuàng)新互聯(lián)
Golang怎么接收前端的參數(shù)?其實并不是特別的難,只需要使用Golang開發(fā)web后臺,需要接收前端傳來的參數(shù)并作出響應就可以了,下面小編給你詳細講解吧。

Golang怎么接收前端的參數(shù)
1、首先,創(chuàng)建一個Golang web服務。
package main
import (
"log"
"fmt"
"net/http"
"html/template"
)
// 返回靜態(tài)頁面
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
Document Golang GET&POST
2、然后編寫前端get post請求,使用了axios庫,請自行引入。
3、接著,在Golang中實現(xiàn)接收get post參數(shù)即可。
一、Golang接收前端GET請求的參數(shù)
// 處理GET請求
func handleGet(writer http.ResponseWriter, request *http.Request) {
query := request.URL.Query()
// 第一種方式
// id := query["id"][0]
// 第二種方式
id := query.Get("id")
fmt.Printf("GET: id=%s\n", id)
fmt.Fprintf(writer, `{"code":0}`)
}
func main() {
// ...
http.HandleFunc("/testGet", handleGet)
// ...
}服務端打印如下:
GET: id=1
二、Golang接收前端POST請求的參數(shù)
// 引入encoding/json包
import (
// ...
"encoding/json"
)
// 處理application/json類型的POST請求
func handlePostJson(writer http.ResponseWriter, request *http.Request) {
// 根據請求body創(chuàng)建一個json解析器實例
decoder := json.NewDecoder(request.Body)
// 用于存放參數(shù)key=value數(shù)據
var params map[string]string
// 解析參數(shù) 存入map
decoder.Decode(¶ms)
fmt.Printf("POST json: username=%s, password=%s\n", params["username"], params["password"])
fmt.Fprintf(writer, `{"code":0}`)
}
func main() {
// ...
http.HandleFunc("/testPostJson", handlePostJson)
// ...
}服務端打印如下:
POST json: username=admin, password=123
以上就是Golang怎么接收前端的參數(shù)的詳細內容,如果想了解更多請關注創(chuàng)新互聯(lián)行業(yè)資訊的其它相關文章!
網站名稱:Golang怎么接收前端的參數(shù)-創(chuàng)新互聯(lián)
轉載源于:http://www.dlmjj.cn/article/cdsecp.html


咨詢
建站咨詢
