Home > Article > Backend Development > Golang’s browser support: building an interactive web
Go builds interactive web applications that run in the browser. Steps: Create Go project and main.go file, add HTTP handler to display messages. Add forms using HTML and JavaScript for user input and submission. Add handling of POST requests in your Go application, receive user messages and return responses. Use the Fetch API to send POST requests and handle server responses.
Go is a versatile programming language that is not limited to back-end development. In this article, we will show you how to easily create interactive web applications using Go to run in the browser.
First, create a new Go project:
go mod init myapp
Next, create a project named main.go
file and add the following code:
package main import ( "fmt" "net/http" ) func main() { // 定义一个处理程序函数,它将在浏览器中渲染一个简单的消息 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello from Go!") }) // 启动 HTTP 服务器侦听端口 8080 上的请求 http.ListenAndServe(":8080", nil) }
Run the Go application using the following command:
go run main.go
Then, open http: //localhost:8080
. You should see the "Hello from Go!" message displayed on the page.
To add interactivity we can use HTML and JavaScript. Add the following to the main.go
file, inside the http.HandleFunc
closure:
// 创建一个简单表单,包含一个输入字段和一个提交按钮 fmt.Fprintf(w, "<form method='POST'><input type='text' name='message'/><input type='submit' value='Send'/></form>")
This will create a form on the page that the user can Enter the message and submit it by pressing the "Send" button.
Next, add the following JavaScript code to the bottom of the HTML page, after the f5a47148e367a6035fd7a2faa965022e
tag:
const form = document.querySelector('form'); form.addEventListener('submit', (e) => { e.preventDefault(); const message = e.target.querySelector('input[name="message"]').value; // 使用 Fetch API 发送 POST 请求 fetch('/', { method: 'POST', body: JSON.stringify({ message }), headers: { 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(data => { // 处理服务器响应 console.log(data); }) .catch(error => { // 处理错误 console.log(error); }); });
This JavaScript code will listen for form submissions, Collect user-entered messages and send POST requests to the Go server using the Fetch API.
In the Go application, add the following code to handle the POST request:
func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { // 解析 JSON 请求正文 var msg Message decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&msg); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // 处理消息并返回响应 fmt.Fprintf(w, "Got your message: %s", msg.Message) } else { // 处理其他请求方法 } }) // 定义一个用于保存消息的类型 type Message struct { Message string `json:"message"` } http.ListenAndServe(":8080", nil) }
With these changes, our web application can now receive input from the user and display a response to it.
Building interactive web applications using Go is easy and powerful. By combining the backend processing power of Go with the frontend capabilities of HTML and JavaScript, you can create rich user experiences that run directly in the browser.
The above is the detailed content of Golang’s browser support: building an interactive web. For more information, please follow other related articles on the PHP Chinese website!