需求:
我们将创建一个简单的Web服务器,能够处理HTTP请求,返回不同的响应,并且支持多个路由。
代码:
package main
import (
"fmt"
"net/http"
)
// Handler for the home page
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the Home Page!")
}
// Handler for the about page
func aboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is the About Page.")
}
// Handler for the contact page
func contactHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Contact us at: contact@ourwebsite.com")
}
func main() {
// Registering handlers with different paths
http.HandleFunc("/", homeHandler)
http.HandleFunc("/about", aboutHandler)
http.HandleFunc("/contact", contactHandler)
// Starting the server on port 8080
fmt.Println("Server started at http://localhost:8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Println("Error starting server:", err)
}
}
解释:
- homeHandler: 响应首页请求。
- aboutHandler: 响应关于页面请求。
- contactHandler: 响应联系方式页面请求。
- 我们使用
http.HandleFunc
来注册路由,每个路由都绑定了一个相应的处理函数。 - 使用
http.ListenAndServe(":8080", nil)
启动服务器,监听在本地的8080端口。
扩展:
- 你可以使用HTML模板动态生成页面内容。
- 可以通过查询参数或者表单接收用户输入并进行处理。