1. 使用自带库 http
import (
"fmt"
"net/http"
)
func myWeb(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "web visit")
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello web")
}
func main() {
handler := http.HandlerFunc(myWeb)
if handler != nil {
fmt.Println("error info : ", handler)
}
fmt.Println("server start, http://localhost:8080")
err := http.ListenAndServe(":8080", handler)
if err != nil {
fmt.Println("error info : ", err)
}
}
这里的http.HandlerFunc是type定义的函数类型:
type HandlerFunc func(ResponseWriter, *Request)
2. 是多函数调用
import (
"fmt"
"net/http"
)
func myWeb(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "web visit")
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello web")
}
func main() {
http.HandleFunc("/hello", hello)
http.HandleFunc("/web", myWeb)
fmt.Println("server start, http://localhost:8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("error info : ", err)
}
}
源码:
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.HandleFunc(pattern, handler)
}