How Golang receives front-end parameters
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
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('/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. 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(¶ms) 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

The latest official news of vivox200ultra has exposed the parameters and price details of vivox200ultra. It is reported that vivox200ultra will be equipped with a 10x periscope super telephoto lens, and the price starts at about 6999 yuan. It can be seen that it occupies an absolute advantage in photography performance. The following are the parameters and prices of vivox200ultra Come and see the details. 1. Parameter configuration details of vivox200ultra 1. Vivox200ultra rendering From the vivo X200 Ultra rendering, the front of the phone adopts a borderless full-screen design, and the visual effect of the entire front of the phone can be said to be very invincible. 2. vivox200ultra has Blackhawk frame

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.
