Golang如何接收前端的参数


本文摘自php中文网,作者angryTom,侵删。

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

Golang如何接收前端的参数

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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

1

2

3

4

5

6

7

8

9

10

<!DOCTYPE html>

<html>

<head>

  <meta charset="UTF-8">

  <title>Document</title>

</head>

<body>

  Golang GET&POST

</body>

</html>

2、然后编写前端get post请求,使用了axios库,请自行引入。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<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学习笔记——面向对象(接口)

golang环形单项链表

golang有指针吗

go语言基础之数组

golang如何实现简单的api网关

必须掌握的golang23种设计模式之工厂方法模式

聊聊promtail的positions

go - 常用签名算法的基准测试

go语言学习(四):数组和切片

详解使用air自动重载代码

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...