GO使用http.HandleFunc()方法搭建一个网站程序,具体方法如下:
使用http.HandleFunc()方法获取参数,并保存为 hello.go文件;
package main
import (
"io"
"log"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello, world!")
}
func main() {
http.HandleFunc("/hello", helloHandler)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
编译 hello.go文件;
$ go run hello.go
最后,在浏览器中访问http://localhost:8080/hello即可;