golang_crud
项目介绍
Golang操作mysql实现crud示例。
软件架构
Golang: go1.11 windows/amd64
Mysql :5.7.9
使用说明
因为使用最go1.11版本,直接使用modules完成依赖包管理;
####使用modules可参考:
####拉取demo:
####切换目录:
cd golang_crud
####启动Demo:
go run main.go
####访问地址
mysql 建表语句保存在users.sql文件中
####说明:
1、使用第三方库
go get github.com/go-sql-driver/mysql
2、解决处理静态文件时样式无法加载出效果的问题 ,之前在main方法中注册了一个路由:
http.HandleFunc("/", Index)
这样是在html中的样式是无法加载出来的。
#####################################################################
###注意以下代码,需要自己定义一个处理路由的方法:
//定义一个实现Handler接口
type Handler interface {
ServeHTTP(http.ResponseWriter,*http.Request)
}
//声明一个结构体
type MyMux struct {
routers map[string]func(http.ResponseWriter, *http.Request)
}
//实现ServeHTTP方法
func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//遍历routers,寻找匹配的path
for path, f := range p.routers {
if ok, _ :=regexp.MatchString("^" + path + "$", r.URL.Path); ok {
f(w, r)
return
}
}
fmt.Fprintf(w, "Error: Dont't match URL '%s'", r.URL.Path)
}
//定义一个静态文件资源
func Static(w http.ResponseWriter, r *http.Request) {
fmt.Println("Deal Static: ", r.URL.Path)
w.Header().Set("Content-Type", "text/css")
http.ServeFile(w, r, "." + r.URL.Path)
}
//在main函数中处理路由变化,注释的代码为旧的版本,不能处理静态资源的代码。
###############################################################