• 用Go编写Web应用程序


    用Go编写Web应用程序

    该系列内容为琦玉老师发布在B站的《使用 Go 语言编写 Web 应用程序》系列课程观后笔记与感悟。
    [https://www.bilibili.com/video/BV1Xv411k7Xn](《使用 Go 语言编写 Web 应用程序》)

    一个Demo

    一来就把我惊艳到了,太方便了。

    import "net/http"
    
    func main() {
    	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    	w.Write([]byte("Hello world"))
            })
    
    	http.ListenAndServe("127.0.0.1:8080", nil)
    }
    

    运行后访问:

    不需要依赖框架,简单地引用net/http包就能实现,太赞了。

    处理(Handle)请求

    每个HTTP请求,Go会创建一个goroutine,由其处理请求。

    http.ListenAndServe()

    第一个参数是网络地址(如果为"",则为all:80)
    第二个参数是handler(如果为nil,就是DefaultServeMux-路由器)

    http.ListenAndServe("127.0.0.1:8080", nil)
    

    等价于

    server := http.Server{
    	Addr:    "127.0.0.1:8080",
    	Handler: nil,
    }
    server.ListenAndServe()
    

    Handler

    Handler是一个接口,定义了一个方法ServeHTTP()
    方法ServeHTTP()有两个参数

    • HTTPResponseWriter
    • 指向Request(struct)的指针
    DefaultServeMux

    多个Handler

    • http.Server中Handler为nil
    • 使用http.Hanlder附加Handler到DefaultServeMux
    import "net/http"
    
    type helloHandler struct{}
    
    func (m *helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    	w.Write([]byte("Hello World"))
    }
    
    type aboutHandler struct{}
    
    func (m *aboutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    	w.Write([]byte("About!"))
    }
    
    func welcome(w http.ResponseWriter, r *http.Request) {
    	w.Write([]byte("Welcome!"))
    }
    
    func main() {
    	a := helloHandler{}
    	b := aboutHandler{}
    
    	server := http.Server{
    		Addr:    "127.0.0.1:8080",
    		Handler: nil,
    	}
    
            //使用http.Handle
    	http.Handle("/hello", &a)
    	http.Handle("/about", &b)
            http.Handle("/welcome2", http.HandlerFunc(welcome))
            //使用http.HandleFunc
    	http.HandleFunc("/home", func(w http.ResponseWriter, r *http.Request) {
    		w.Write([]byte("Home!"))
    	})
    	http.HandleFunc("/welcome", welcome)
    	server.ListenAndServe()
    }
    

    内置的Handler

    • http.NotFoundHandler
      给每个请求的响应都是404
    • http.RedirectHandler
      使用给定的状态码将请求跳转到指定的页面
    • http.StripPrefix
      去掉请求中指定的前缀,调用另一个handler
    • http.TimeoutHandler
      在指定时间内运行传入的handler
    • http.FileServer
      使用基于root的文件系统来响应请求
  • 相关阅读:
    【图像处理】【SEED-VPM】7.ubuntu10.04下 TFTP,NFS 安装指南
    【图像处理】【SEED-VPM】6.文件目录结构
    【DIY】【外壳】木板 & 亚克力 加工
    【图像处理】【SEED-VPM】5.uImage的烧写 & NFS烧写文件系统
    【PCB】【AD使用】Altium Designer 的entry sheet ,offsheet和port作用
    【PCB】【项目记录】AWG任意波形产生器
    【图像处理】【SEED-VPM】4.串口调试信息
    【图像处理】【SEED-VPM】3.外设信息
    【图像处理】【SEED-VPM】2.接口
    【图像处理】【SEED-VPM】1.注意点
  • 原文地址:https://www.cnblogs.com/muphalem/p/13923521.html
Copyright © 2020-2023  润新知