您好,欢迎访问一九零五行业门户网

Golang如何接收前端的参数

使用golang开发web后台,需要接收前端传来的参数并作出响应,那么golang该如何接收前端的参数呢?一起来看下吧。
golang如何接收前端的参数
1、首先,创建一个golang web服务。
package mainimport ( "log" "fmt" "net/http" "html/template")// 返回静态页面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请求,使用了axios库,请自行引入。
<script> axios.get('/testget', { params: { id: 1, } }).then((response) => { console.log(response); }); // post数据const postdata = { username: 'admin', password: '123',};axios.post('/testpostjson', postdata).then((response) => { console.log(response);});</script>
3、接着,在golang中实现接收get post参数即可。
一、golang接收前端get请求的参数
// 处理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请求的参数
// 引入encoding/json包import ( // ... "encoding/json")// 处理application/json类型的post请求func handlepostjson(writer http.responsewriter, request *http.request) { // 根据请求body创建一个json解析器实例 decoder := json.newdecoder(request.body) // 用于存放参数key=value数据 var params map[string]string // 解析参数 存入map decoder.decode(&params) 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知识请关注golang教程栏目。
以上就是golang如何接收前端的参数的详细内容。
其它类似信息

推荐信息