使用go的http包搭建简单的服务器
package main
import (
"fmt"
"log"
"net/http"
"strings"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析参数,默认是不会解析的
fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["friend"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello my friend!") //这个写入到w的是输出到客户端的
}
func main() {
http.HandleFunc("/", sayhelloName) //设置访问的路由
err := http.ListenAndServe(":8080", nil) //设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
go run 运行,这个时候其实已经在8080端口监听http请求了。
浏览器中输入http://localhost:8080/就可以看到一行英文:
“Hello my friend!”了。
下面看一下http包的源码,了解 web 服务器处理 http 协议的过程.
主要分析main()中的两个函数:http.HandleFunc(“/”, sayhelloName)和http.ListenAndServe(“:8080”, nil)
先看http.HandleFunc(“/”, sayhelloName)的定义。该函数给DefaultServeMux中相应的路由注册处理函数。
// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.HandleFunc(pattern, handler)
}
继续追踪方法DefaultServeMux.HandleFunc(pattern, handler)
// HandleFunc registers the handler function for the given pattern.
func (mux *Serve