golang从0到1实战系统三十六:GO 搭建一个 web 服务器
    		       		warning:
    		            这篇文章距离上次修改已过451天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "fmt"
    "log"
    "net/http"
)
 
func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}
 
func main() {
    http.HandleFunc("/hello", helloHandler)
 
    fmt.Println("Starting server on :8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}这段代码创建了一个简单的Web服务器,监听8080端口,并对"/hello"路径的请求进行响应。它使用了net/http标准库中的ListenAndServe函数来启动服务器,并使用http.HandleFunc注册了一个处理函数helloHandler来处理特定路径的HTTP请求。当服务器启动并运行时,它会在控制台打印一条消息,并等待传入的HTTP请求。如果服务器遇到错误,会使用log包中的Fatal函数记录错误并退出程序。
评论已关闭