1. Hello World HTTP 服务器

Hello World HTTP 服务器 学习卡片

任务说明

使用 Go 标准库 net/http 创建一个 HTTP 服务器,监听本机端口,对根路径 / 的 GET 请求返回文本 Hello, World。这是 Go 后端开发中最基础的入门案例,用于验证开发环境与 HTTP 服务的基本工作链路。

实现代码

创建文件 main.go,内容如下:

package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    // 仅处理根路径,其他路径返回 404
    if r.URL.Path != "/" {
        http.NotFound(w, r)
        return
    }
    // 仅支持 GET 方法
    if r.Method != http.MethodGet {
        w.WriteHeader(http.StatusMethodNotAllowed)
        fmt.Fprintf(w, "Method not allowed")
        return
    }
    fmt.Fprint(w, "Hello, World")
}

func main() {
    http.HandleFunc("/", helloHandler)
    // 监听 8080 端口
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Printf("Server error: %v\n", err)
    }
}

代码说明

上述代码的核心逻辑如下:

  • helloHandler 是根路径的请求处理函数,通过 r.URL.Path 判断请求路径,非根路径直接返回 404;通过 r.Method 限制仅接受 GET 请求,其他方法返回 405。
  • http.HandleFunc("/", helloHandler) 将根路径路由注册到处理函数。
  • http.ListenAndServe(":8080", nil) 启动服务器并监听 8080 端口,使用默认的多路复用器。

运行与验证

在项目目录下执行以下命令启动服务器:

go run main.go

服务器启动后,打开另一个终端窗口,使用 curl 命令验证:

curl http://localhost:8080/

预期输出:Hello, World

再验证非根路径与错误方法:

curl http://localhost:8080/other
# 预期输出:404 page not found

curl -X POST http://localhost:8080/
# 预期输出:Method not allowed

判定标准:当 curl http://localhost:8080/ 返回 Hello, World,且非根路径返回 404、POST 请求返回 405 时,本案例实现正确。

请求处理流程

客户端 (curl) HTTP 服务器 GET / HTTP/1.1 处理逻辑 路径是否为 "/" ? → 否:返回 404 → 是:检查方法是否为 GET HTTP/1.1 200 OK Body: "Hello, World"

上图展示了客户端发起 GET 请求后,服务器根据路径与方法进行判断,最终返回 Hello, World 的完整流程。