教程 go tutorial

net/http 基本使用

1. 创建简单 HTTP 服务器

go
package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, World!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

`

2. 处理请求和响应

  • 通过 http.ResponseWriter 写响应内容
  • 通过 *http.Request 获取请求信息

3. 启动服务器

调用 http.ListenAndServe 监听端口,启动服务。


net/http 包是 Go 标准库中用于 Web 开发的基础组件。