package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", index) // index 为向 url发送请求时,调用的函数 log.Fatal(http.ListenAndServe("localhost:8000", nil)) } func index(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "C语言中文网") }使用
go run
命令运行上面的代码:
go run main.go
运行之后并没有什么提示信息,但是命令行窗口会被占用(不能再输入其它命令)。这时我们在浏览器中输入 localhost:8000 可以看到下图所示的内容,则说明我们的服务器成功运行了。提示:运行 Web 服务器会占用命令行窗口,我们可以使用 Ctrl+C 组合键来退出。
上面的代码只是展示了 Web 服务器的简单应用,下面我们来完善一下,为这个服务器添加一个页面并设置访问的路由。<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>C语言中文网</title> </head> <body> <h1>C语言中文网</h1> </body> </html>然后将我们上面写的 Web 服务器的代码简单修改一下,如下所示:
package main import ( "io/ioutil" "log" "net/http" ) func main() { // 在/后面加上 index ,来指定访问路径 http.HandleFunc("/index", index) log.Fatal(http.ListenAndServe("localhost:8000", nil)) } func index(w http.ResponseWriter, r *http.Request) { content, _ := ioutil.ReadFile("./index.html") w.Write(content) }使用
go run
命令运行:
go run main.go
运行成功后,在浏览器中输入 localhost:8000/index 就可以看到我们所添加的页面了,如下图所示:Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有