用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的文件系统来响应请求
posted @ 2020-11-04 00:16  Muphalem  阅读(306)  评论(0编辑  收藏  举报
/* 看板娘 */