以下是一个简单的 golang http 服务端代码示例:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
}
func main() {
http.HandleFunc("/", helloHandler)
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Println(err)
}
}
这个代码创建了一个 helloHandler 函数,用于处理 / 路径的请求。当收到该路径的请求时,函数会向客户端发送 Hello, world! 的字符串。
然后,在 main 函数中,我们通过调用 http.HandleFunc 来将 helloHandler 函数注册为路由器的处理函数。最后,我们使用 http.ListenAndServe 启动服务器并监听来自客户端的连接。
如果你在本地运行此代码,则可以在浏览器中访问 http://localhost:8080/ 来测试它是否正常工作。




