第一个HTTP应用:Hello, World!
让我们从最经典的Hello, World!开始:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
代码解析:
handler: 定义一个处理HTTP请求的函数,它接收两个参数:http.ResponseWriter用于写入响应,http.Request包含请求的信息。fmt.Fprintf(w, "Hello, World!"): 将 "Hello, World!" 写入响应。http.HandleFunc("/", handler): 将根路径 "/" 注册到handler函数,当有请求访问根路径时,handler函数会被调用。http.ListenAndServe(":8080", nil): 启动一个HTTP服务器,监听8080端口。
将这段代码保存为 main.go 文件,然后在终端中运行 go run main.go。
打开你的浏览器,访问 http://localhost:8080,你就能看到 "Hello, World!" 了!
处理请求参数
HTTP请求通常会携带参数,我们可以通过 r.URL.Query() 来获取这些参数:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
name = "World"
}
fmt.Fprintf(w, "Hello, %s!", name)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
现在,你可以访问 http://localhost:8080?name=testName,浏览器会显示 "Hello, testName!"。 如果你访问 http://localhost:8080,浏览器会显示 "Hello, World!"。
处理POST请求
除了GET请求,我们还需要处理POST请求。我们可以通过 r.ParseForm() 解析POST请求的表单数据,然后通过 r.FormValue() 获取表单字段的值:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
r.ParseForm()
name := r.FormValue("name")
fmt.Fprintf(w, "Hello, %s!", name)
} else {
fmt.Fprintf(w, "Please use POST method to send your name.")
}
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
你需要使用工具(例如Postman)或者编写一个简单的HTML表单来发送POST请求。
返回JSON数据
在实际开发中,我们经常需要返回JSON数据。可以使用 encoding/json 包来将Go语言的数据结构转换为JSON格式:
package main
import (
"encoding/json"
"net/http"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func handler(w http.ResponseWriter, r *http.Request) {
user := User{
Name: "John Doe",
Age: 30,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
这段代码定义了一个 User 结构体,并使用 json:"name" 和 json:"age" 来指定JSON字段的名称。然后,我们创建了一个 User 实例,并使用 json.NewEncoder(w).Encode(user) 将其转换为JSON格式并写入响应。如果你访问 http://localhost:8080,浏览器会显示 {"name":"John Doe","age":30}。
总结
通过这篇文章,你已经掌握了Go语言HTTP应用开发的基本知识,包括:
- 创建HTTP服务器
- 处理GET和POST请求
- 获取请求参数
- 返回JSON数据
希望这篇文章能帮助你入门Go语言的HTTP应用开发。如果你有任何问题,欢迎在评论区留言!
感谢阅读!如果你觉得这篇文章对你有帮助,请分享给你的朋友们,让更多的人一起学习Go语言!