GO搭建一个web服务器
package main
// file name: goweb.go
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(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello astaxie!") // 这个写入到 w 的是输出到客户端的
}
func main() {
http.HandleFunc("/", sayHelloName) // 设置访问的路由
err := http.ListenAndServe(":9000", nil)
if err != nil {
log.Fatal("ListenAndServer :", err)
}
}
go run goweb.go
- 查看浏览器页面:http://localhost:9000
- 查看浏览器页面:http://localhost:9000/?url_long=111&url_long=222
web工作方式的几个概念
以下均是服务器端的几个概念
- Request:用户请求的信息,用来解析用户的请求信息,包括post、get、cookie、url等信息
- Response:服务器需要反馈给客户端的信息
- Conn:用户的每次请求链接
- Handler:处理请求和生成返回信息的处理逻辑