1. 背景
学习 go 相关的知识,了解到 go 语言的一些特性,可以起服务器,这个时候就开始了学习路线ing
2. 为什么选择 Go 语言构建 Web 服务器
在选择一门语言构建 Web 服务器时,性能、并发性和开发效率是关键因素。而 Go 语言在这些方面都表现出色:
-
高性能: Go 语言被设计成一门编译型语言,具有接近原生代码的性能。这使得 Go 语言的 Web 服务器能够处理大量的并发连接和请求。
-
并发性: Go 语言内置了 Goroutine 和 Channel 的支持,使得并发编程变得非常容易。这对于 Web 服务器来说至关重要,因为它们需要同时处理多个请求。
-
简洁的语法: Go 语言拥有简洁的语法和清晰的代码结构,使得开发者可以更加专注于业务逻辑,而不必过多关注底层细节。
3. 简单示例: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)
var port = ":9090"
if err := http.ListenAndServe(port, nil); err != nil {
panic(err)
}
}
4. 多个路由示例
package main
import (
"fmt"
"net/http"
)
func main() {
// 主页路由
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "welcome to my website!")
})
// 关于我们页面路由
http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "this is about us page...")
})
// 联系我们页面路由
http.HandleFunc("/contact", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "this is contact us page...")
})
// 启动服务器,在9000端口监听
err := http.ListenAndServe(":9000", nil)
if err != nil {
fmt.Printf("Failed to start the server:%v\n", err)
}
}