Home >Backend Development >Golang >How Golang receives front-end parameters

How Golang receives front-end parameters

angryTom
angryTomOriginal
2020-03-18 13:46:106003browse

Using Golang to develop the web backend requires receiving parameters from the front end and responding to them. So how does Golang receive the parameters from the front end? Let’s take a look together.

How Golang receives front-end parameters

How Golang receives front-end parameters

1. First, create a Golang web service.

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. Then write the front-end get post request, using the axios library, please introduce it yourself.

<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. Next, receive the get post parameters in Golang.

1. Golang receives the parameters of the front-end GET request

// 处理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)

    // ...
}

The server prints the following:

GET: id=1

2 , Golang receives the parameters of the front-end POST request

// 引入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)

    // ...
}

The server prints as follows:

POST json: username=admin, password=123

For more golang knowledge, please pay attention to the PHP Chinese websitegolang tutorial Column.

The above is the detailed content of How Golang receives front-end parameters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How Golang receives inputNext article:How Golang receives input