需求
最简单的 go http 例子
编码
- main.go
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}
func main() {
// 注册处理函数
http.HandleFunc("/", handler)
// 启动 HTTP 服务器并监听端口
port := 8080
fmt.Printf("Server is listening on :%d...\n", port)
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
if err != nil {
fmt.Println("Error:", err)
}
}
2023年9月25日大约 12 分钟