Golang net/http
时间: 2024-01-19 18:04:50 浏览: 20
Golang的标准库中有一个包叫做"net/http",它提供了一个HTTP客户端和HTTP服务器的实现。
在使用"net/http"包之前,您需要先设置HTTP服务器的路由和处理程序。以下是一个简单的HTTP服务器示例:
```go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", helloWorldHandler)
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println(err)
}
}
func helloWorldHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
}
```
在上面的示例中,我们首先使用`http.HandleFunc`函数将路由"/"映射到名为"helloWorldHandler"的处理程序函数。然后,我们使用`http.ListenAndServe`函数启动HTTP服务器并将其绑定到本地端口8080上。
当我们访问"http://localhost:8080/"时,服务器将调用"helloWorldHandler"函数并在响应中返回"Hello, World!"。
这只是一个简单的例子,"net/http"包还提供了许多其他功能,例如处理HTTP请求和响应数据、设置HTTP头、处理表单数据等。