MIT6.5830 Lab1-Go tutorial实验记录(一

MIT6.5830 Lab1-Go tutorial实验记录(一) – WhiteNight's Site

标签:Golang, 数据库

编写一个简单的http server。

前言

MIT数据库系统实验

在网上看到了这么个实验,刚好对golang和数据库比较感兴趣,于是开始跟着做实验。下面放两个链接,前者是课程官网;后者是我fork的代码仓库,可以参考我的代码或者直接去看源仓库。

课程地址 实验代码参考

我自己是go和数据库的初学者,所以都是靠自己摸索。反正最后能实现实验要求的功能就OK了。

实验要求

波士顿MBTA(MIT所在地的一个交通运输管理局)的数据可视化

简单来说,给了一个800mb的sqlite数据库文件。现在需要你把“乘客量”这个数据进行可视化。总的来说就是需要让你编写http server以让后端的数据呈现在前端的页面上,其中还包括了处理数据等等。

你已经学会了GO的数据类型,接下来就开始实验吧!请创建一个简单的http server。在做实验前还是得了解GO的基础知识的,不过不了解也没问题,本文会讲的非常非常详细。

实验步骤

创建http server

clone完仓库后,别忘了下载mbta.sqlite。具体的文件结构已经在md里面写了,这里就不再说了。

打开main.go,我们可以看到第一个TODO

package main

func main() {
	// TODO: some code goes here
	// Fill out the HomeHandler function in handlers/handlers.go which handles the user's GET request.
	// Start an http server using http.ListenAndServe that handles requests using HomeHandler.
	
}

要求我们先补全HomeHandler,HomeHandler是什么,不知道。先不管。但我们知道它是一个handler。

  • Handler:又叫处理器,在这里用于处理HTTP请求。

根据GO的官方文档,我们可以还可以得到一个创建http server的代码例

http.Handle("/foo", fooHandler)

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

log.Fatal(http.ListenAndServe(":8080", nil))

这里列出了两种注册Handler的方法:

  • http.Handle(A,B):A为HTTP路由。B为已有的Handle对象。
  • http.HandleFunc(A,B):A为HTTP路由。B为处理函数。

简单来说,当用户请求访问对应的路由时(比如https://baidu.com/hello中的/hello),就会调用Handler的方法来响应用户的请求。

接下来我们看下HomeHandler,这里已经说明了它是个function,那我们就用HandleFunc。而ListenAndServer同样接受两个参数,前者为要监听的端口,后者默认nil即可。

package main

import (
	"fmt"
	"main/handlers"
	"net/http"
)

func main() {
	// TODO: some code goes here
	// Fill out the HomeHandler function in handlers/handlers.go which handles the user's GET request.
	// Start an http server using http.ListenAndServe that handles requests using HomeHandler.

	http.HandleFunc("/", handlers.HomeHandler)
	port := 8080
	http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}

在调试前,由于GO语言不允许“变量定义但不使用”,你还需要“使用”handlers文件夹下的handlers.go中的db,tmpl,data。毕竟你现在还不知道这几个变量能干什么,所以用空白标识符“_”即可。

_=db;
_=tmpl;
_=data;

同时为了方便调试,可以加个打印看看效果。

// TODO: some code goes here
// Get the chart data from RidershipDB
_ = db
fmt.Fprintln(w, "Hello, this is the home page!")
// TODO: some code goes here
// Plot the bar chart using utils.GenerateBarChart. The function will return the bar chart
// as PNG byte slice. Convert the bytes to a base64 string, which is used to embed images in HTML.

按f5调试,浏览器访问localhost:8080。正常显示界面

下一篇文章我们将实现从RidershipDB中拿到图像数据等操作。本文就先到这里了。

猜你喜欢

转载自blog.csdn.net/white_night_SZTU/article/details/133861666