每日一Go-16、Go语言实战-构建Web服务器

40 阅读2分钟

在 Go 语言中,构建一个 Web 服务器比你想象的更简单。标准库已经为我们准备好了功能强大的 net/http 包,它能轻松实现 HTTP 服务、路由分发、请求处理等核心功能。

1、快速上手

只需要几行代码就能跑起来一个Web服务:

package main
import (
    "fmt"
    "net/http"
)
func main() {
    // 首页 "/"
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, Go Web Server!")
    })
    // 启动服务器,监听 8080 端口
    fmt.Println("服务器启动于 http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

运行后,浏览器访问http://localhost:8080

图片

2、处理路由

通过 http.HandleFunc 为不同的 URL 路径绑定处理函数

package main
import (
    "fmt"
    "net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, world!")
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "About me")
}
func main() {
    http.HandleFunc("/", helloHandler)
    http.HandleFunc("/about", aboutHandler)
    fmt.Println("服务启动于 http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

运行后,浏览器访问http://localhost:8080/about

图片

3、处理不同的请求(GET/POST/PUT/DELETE)

package main
import (
    "fmt"
    "net/http"
)
func formHandler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case http.MethodGet:
        html := `这是get请求`
        fmt.Fprint(w, html)
    case http.MethodPost:
        html := `这是post请求`
        fmt.Fprint(w, html)
    case http.MethodPut:
        html := `这是put请求`
        fmt.Fprint(w, html)
    case http.MethodDelete:
        html := `这是delete请求`
        fmt.Fprint(w, html)
    default:
        http.Error(w, "不支持的请求", http.StatusMethodNotAllowed)
    }
}
func main() {
    http.HandleFunc("/form", formHandler)
    fmt.Println("访问 http://localhost:8080/form")
    http.ListenAndServe(":8080", nil)
}

4、分离路由与业务逻辑

这利用了接口 http.Handler 的强大设计,使我们可以创建灵活的中间件和自定义路由系统。


package main
import (
    "fmt"
    "net/http"
)
// 自定义路由结构体
type MyServer struct{}
func (s *MyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    switch r.URL.Path {
    case "/":
        fmt.Fprint(w, "首页")
    case "/hello":
        fmt.Fprint(w, "你好,Go Web!")
    default:
        http.NotFound(w, r)
    }
}
func main() {
    server := &MyServer{}
    fmt.Println("服务器启动:http://localhost:8080")
    http.ListenAndServe(":8080", server)
}

5、总结: net/http 的核心思想

功能关键接口/函数说明
启动服务器http.ListenAndServe(":8080", server)启动HTTP服务
注册路由http.HandleFunc("/form", formHandler)简单注册路由函数
处理请求func(w http.ResponseWriter, r *http.Request)核心处理函数
写响应fmt.Fprint(w, data)向客户端输出内容
区分请求方法r.MethodGETPOSTPUTDELETE等

人生就如同Web服务器。不同的人、事,就像不同的请求路径。我们要学会用不同的方式去回应——有的需要马上答复(GET),有的需要花时间思考(POST)。有时会出错(404),有时会崩溃(500),但只要还在运行,就能重启、修复、继续服务。人生的关键,是保持“在线”。


源码地址

1、公众号“Codee君”回复“源码”获取源码

2、pan.baidu.com/s/1B6pgLWfS…


如果您喜欢这篇文章,请您(点赞、分享、亮爱心),万分感谢!