web的工作方式
Go 搭建一个web服务
func main(){
http.HandleFunc("/", sayHelloName) // 设置访问的路由
err := http.ListenAndServe(":8088",nil) // 设置监听的端口
if err != nil {
log.Fatal("listen and server: ",err)
}
}
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["url_long"])
for k,v:=range r.Form{
fmt.Println("key",k," val:",strings.Join(v,""))
}
fmt.Fprintf(w, "Hello word") // 这个写入到 w 的是输出到客户端的
}
结果
自己添加路由
type MyMux struct {
}
func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request){
if r.URL.Path == "/" {
sayHelloName(w, r)
return
}
http.NotFound(w, r)
return
}
func main(){
mux := &MyMux{}
http.ListenAndServe(":8088",mux) //加载自己的路由规则
}
func sayHelloName(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello word!")
}