>  기사  >  백엔드 개발  >  Golang이 프런트엔드 매개변수를 수신하는 방법

Golang이 프런트엔드 매개변수를 수신하는 방법

angryTom
angryTom원래의
2020-03-18 13:46:105877검색

Golang을 사용하여 웹 백엔드를 개발하려면 프런트엔드에서 매개변수를 받고 응답해야 합니다. 그렇다면 Golang은 프런트엔드에서 매개변수를 어떻게 받나요? 함께 살펴보겠습니다.

Golang이 프런트엔드 매개변수를 수신하는 방법

Golang이 프런트엔드 매개변수를 받는 방법

1. 먼저 Golang 웹 서비스를 만듭니다.

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. 그런 다음 axios 라이브러리를 사용하여 프론트엔드 get post 요청을 작성하고 직접 소개해주세요.

<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 매개변수를 받습니다.

1. 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

2. 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)

    // ...
}

The 서버는 다음과 같이 인쇄합니다.

POST json: username=admin, password=123

More 더 많은 golang 지식을 알고 싶다면 PHP 중국어 웹사이트의 golang tutorial 칼럼을 주목하세요.

위 내용은 Golang이 프런트엔드 매개변수를 수신하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.