web应用小程序示例
web应用小程序,最棘手的是函数参数能否做参数和返回值的问题
处理函数必须接受一个http.ResponseWriter值和一个指向http.Request值的指针来作为参数
package main
import (
"log"
"net/http"
)
// writer用于更新发送到浏览器的响应的值
// request 表示来自浏览器的请求的值
func viewHandler(writer http.ResponseWriter, request *http.Request) {
message := []byte("hello,web!")
_, err := writer.Write(message) //《---向响应中添加helloweb
if err != nil {
log.Fatal(err)
}
}
func main() {
http.HandleFunc("/hello", viewHandler) //如果我们收到一个以“/hello”结尾的url请求,那么调用xx函数生成响应
err := http.ListenAndServe("localhost:8080", nil) //监听浏览器的请求,并对其做出响应
log.Fatal(err)
//退出终端 按下 ctrl+c
}
/*
对于不同的资源路径做出不同的响应 /hello ->> viewHanler响应
*/
自己尝试编写不同URL对应不同的响应
package main
import (
"log"
"net/http"
)
func write(writer http.ResponseWriter, message string) {
_, err := writer.Write([]byte(message))
if err != nil {
log.Fatal(err)
}
}
func d(writer http.ResponseWriter, request *http.Request) {
write(writer, "z")
}
func e(writer http.ResponseWriter, request *http.Request) {
write(writer, "x")
}
func f(writer http.ResponseWriter, request *http.Request) {
write(writer, "y")
}
func main() {
http.HandleFunc("/a", f) //将 f 函数传递给HandFunc ---->一级函数
http.HandleFunc("/b", d)
http.HandleFunc("/c", e)
err := http.ListenAndServe("localhost:4567", nil)
log.Fatal(err)
}