下面是一个简单的 Go HTTP Server 的示例代码:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	// 定义路由处理函数
	http.HandleFunc("/", helloHandler)

	// 启动服务器并监听端口
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("启动服务器失败:", err)
	}
}

// 处理路由请求的函数
func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, World!")
}

这是一个最基本的 HTTP Server 的实现。它使用 http.HandleFunc 函数来注册一个路由处理函数 helloHandler,当收到来自根路径的请求时,该函数会将 "Hello, World!" 字符串写入到 ResponseWriter 中,返回给客户端。

使用 http.ListenAndServe 函数来启动服务器,并指定监听的端口号为 8080。如果启动服务器失败,会打印出错误信息。

你可以将上述代码保存为一个 .go 文件,然后使用 go run 命令来运行它:

go run main.go

接下来,你可以在浏览器中访问 http://localhost:8080,就会看到 "Hello, World!" 字符串显示在页面上

go 实现一个http server

原文地址: https://www.cveoy.top/t/topic/hMmq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录