Skip to the content.

Controller : Go HTTP Server

controller包用于响应请求,进行逻辑处理

HTTP Server 的作用

用Go实现Web应用主要用到其内置的net/http包,能够轻松实现 HTTP Server 的功能。HTTP Server 的主要作用包括:

参考Go Web Examples

Process dynamic requests

HTTP Server 的主要功能之一就是处理来自浏览器的动态请求,响应机制为一个url对应一个响应函数。在Go中每一个响应函数称为handler,形式如下:

func (w http.ResponseWriter, r *http.Request)

其中 http.Request 类型中包含从浏览器传过来的数据。在每一个handler中编写具体的逻辑

在主函数中通过http.HandleFunc方法注册handler函数,将url路径与响应函数绑定起来。

http.HandleFunc("/",Hello)

 func Hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Welcome to my website!")
}

Serving static assets

通常将一些静态的文件如CSSjs和图片,存放在同一个文件夹中。然后生成一个FileServer类型用于统一路由。这样html中的一些静态文件路径,就可以直接都从指定的路径开始写。

Go生成FileServer的方法:

fs := http.FileServer(http.Dir("static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

Accept connections

就是监听请求

http.ListenAndServe(":80", nil)

代码结构

booklist项目采用面向对象的方法写controller,即定义一个Controller 结构体,每一个hanler函数作为它的一个方法。逻辑如下

// booklist/controller/handlers.go
type Controller struct {
	M		model.BooklistModel
	Init     bool
}

func (c *Controller) ShowView(w http.ResponseWriter, r *http.Request, tmpl string, data interface{}) {}

func (c *Controller) Welcome(w http.ResponseWriter, r *http.Request,) {}

func (c *Controller) AddBookView(w http.ResponseWriter, r *http.Request){}

func (c *Controller) AddBook(w http.ResponseWriter, r *http.Request){}

//  booklist/main.go
func main() {
    
	//创建controller实例
	controller := controller.Controller{}
	m := model.BooklistModel{}
	m.Init()
	controller.M = m


	//创建服务器实例,指定静态文件所在路径
	fs := http.FileServer(http.Dir("static/"))
	http.Handle("/static/",http.StripPrefix("/static/", fs))

	http.HandleFunc("/", controller.Welcome)
	http.HandleFunc("/add.html", controller.AddBookView)
	http.HandleFunc("/add", controller.AddBook)

	//启动,监听
	http.ListenAndServe(":8080",nil)


}

Handler中的数据处理

handler需要干两件事:

逻辑如下,ShowView 方法负责统一生成Tempate,其他方法负责处理具体数据。

AddBook为例,分为三步

func (c *Controller) AddBook(w http.ResponseWriter, r *http.Request) {
	//1.接收数据
	BookName := r.FormValue("BookName")
	FinishedTime := r.FormValue("FinishedTime")
	Comments := r.FormValue("Comments")
	flag := false

	//2.追加数据
	if BookName != "" {
		flag = true
		c.M.AddBook(BookName, FinishedTime, Comments)

		//3.传入结构体
		c.ShowView(w, r, "add.html", struct {
			Flag  bool
		}{
			flag,
		})
	}else {
		c.ShowView(w, r, "add.html", nil)
	}

}

Template实例在融合数据时,传入的必须是一个结构体

err = resultTemplate.Execute(w, data) //data is a struct

Introduction

View : html and css

Controller : Go http package

Model : database