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参数即可。

阅读剩余部分

相关阅读 >>

go 反射解析结构体标签tag

go语言 defer详解

go reflect

golang怎么判断channel是否关闭

08 golang引用类型——切片

go基础及语法(二)

golang写爬虫乱码怎么办

golang 怎么调用c代码

手撸golang 结构型设计模式 桥接模式

手撸golang 结构型设计模式 代理模式

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




打赏

取消

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

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

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

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

评论

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