登录  /  注册
首页 > 后端开发 > Golang > 正文

Golang如何接收前端的参数

angryTom
发布: 2020-03-18 13:46:10
原创
5708人浏览过

使用golang开发web后台,需要接收前端传来的参数并作出响应,那么golang该如何接收前端的参数呢?一起来看下吧。

Golang如何接收前端的参数

Golang如何接收前端的参数

1、首先,创建一个Golang web服务。

package main

import (
    "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(&#39;/testGet&#39;, {
    params: {
      id: 1,
    }
  }).then((response) => {
    console.log(response);
  });
  
  // POST数据
const postData = {
  username: &#39;admin&#39;,
  password: &#39;123&#39;,
};

axios.post(&#39;/testPostJson&#39;, 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知识请关注PHP中文网golang教程栏目。

以上就是Golang如何接收前端的参数的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号