goweb之书城基本CRUD增删改查

无法加载静态资源
在主函数中添加一条语句:

// 设置处理静态资源
	http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("views/static"))))
	http.HandleFunc("/index",IndexHandler)
	http.ListenAndServe(":8080",nil)

以static打头的以内静态资源得到访问,但是pages下的login/cart等还需再次配置.
goweb之书城基本CRUD增删改查

// 设置处理静态资源
	http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("views/static"))))
	// 直接通过a标签点击去往页面
	http.Handle("/pages/",http.StripPrefix("/pages/",http.FileServer(http.Dir("views/pages"))))

  1. 连接数据库
package utils0610

import (
	"database/sql"
	_"github.com/mysql-master" // 勿忘引入

)

var(
	Db *sql.DB
	err error
)

func init(){
	Db,err = sql.Open("mysql","root:123456@tcp(192.168.58.129:3306)/bookstore")
	if err!=nil{
		panic(err.Error())
	}
}
  1. bookdao中操作数据库添加查询方法,由于返回图书列表,故定义结构体指针切片,返回切片类型
/*
查:查询所有图书列表
*/
func GetBooks() ([]*model0610.Book, error) {
	sqlStr := "select id,title,author,price,sales,stock,img_path from books"
	rows, err := utils0610.Db.Query(sqlStr)
	if err != nil {
		return nil, err
	}
	var books []*model0610.Book // 结构体指针切片
	for rows.Next() {
		book := &model0610.Book{} // 定义一个结构体
		rows.Scan(&book.Id, &book.Title, &book.Author, &book.Price, &book.Sales, &book.Stock, &book.ImgPath)
		// 将book添加到切片中
		books = append(books, book)
	}
	return books, nil
}
  1. 在controller控制层中,进行模板解析文件,并执行Execute方法。进行视图的跳转
/*
获取所有图书控制器
 */
func GetBooks(w http.ResponseWriter,r *http.Request){
	books, _ := dao0610.GetBooks()
	t := template.Must(template.ParseFiles("views/pages/manager/book_manager.html"))
	t.Execute(w,books)
}
  1. 定义请求url映射,即浏览器发送给服务端的url请求映射目的地。
// 获取所有图书
	http.HandleFunc("/getBooks",controller0610.GetBooks)
  1. 前端列表展示代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书管理</title>
<link type="text/css" rel="stylesheet" href="/static/css/style.css" >
</head>
<body>
	
	<div id="header">
			<img class="logo_img" alt="" src="/static/img/logo.gif" >
			<span class="wel_word">图书管理系统</span>
			<div>
				<a href="/pages/manager/book_manager.html">图书管理</a>
				<a href="/">返回商城</a>
			</div>
	</div>
	
	<div id="main">
		<table>
			<tr>
				<td>名称</td>
				<td>价格</td>
				<td>作者</td>
				<td>销量</td>
				<td>库存</td>
				<td colspan="2">操作</td>
			</tr>
			{{range .}}
			<tr>
				<td>{{.Title}}</td>
				<td>{{.Price}}</td>
				<td>{{.Author}}</td>
				<td>{{.Sales}}</td>
				<td>{{.Stock}}</td>
				<td><a href="/getBookById?bookId={{.Id}}">修改</a></td>
				<td><a href="/deleteBook?bookId={{.Id}}">删除</a></td>
			</tr>

			{{end}}
			<td><a href="/pages/manager/book_edit.html">添加图书</a></td>
		</table>
	</div>
	
	<div id="bottom">
		<span>
			尚硅谷书城.Copyright &copy;2015
		</span>
	</div>
</body>
</html>

bookdao

/*
增:新增图书
*/
func AddBook(b *model0610.Book) error {
	//写sql语句
	slqStr := "insert into books(title,author,price,sales,stock,img_path) values(?,?,?,?,?,?)"
	//执行
	_, err := utils0610.Db.Exec(slqStr, b.Title, b.Author, b.Price, b.Sales, b.Stock, b.ImgPath)
	if err != nil {
		return err
	}
	return nil
}

bookController

/*
新增图书,获取浏览器表单信息
*/
func AddBook(w http.ResponseWriter,r *http.Request){
	title := r.PostFormValue("title")
	author := r.PostFormValue("author")
	price := r.PostFormValue("price") // 得到的是string类型,但原本是float64
	priceFloat64, _ := strconv.ParseFloat(price, 64)
	sales := r.PostFormValue("sales")
	salesInt, _ := strconv.ParseInt(sales, 10, 0)
	stock := r.PostFormValue("stock")
	stockInt, _ := strconv.ParseInt(stock, 10, 0)
	book := &model0610.Book{
		Title: title,
		Author: author,
		Price: priceFloat64,
		Sales: int(salesInt),
		Stock: int(stockInt),
		ImgPath: "/static/img/default.jpg",
	}
	dao0610.AddBook(book)
	// 跳转到显示列表,再次查询才跳转
	GetBooks(w,r)
}

main.go

// 新增图书
	http.HandleFunc("/addBook",controller0610.AddBook)

bookdao

/*
删:删除图书
*/
func DeleteBook(id int) error {
	sqlStr := "delete from books where id = ?"
	_, err := utils0610.Db.Exec(sqlStr, id)
	if err != nil {
		return err
	}
	return nil
}

bookController

/*
删除图书
 */
func DeleteBookById(w http.ResponseWriter,r *http.Request){
	idString := r.FormValue("bookId")
	idInt, _ := strconv.ParseInt(idString, 10, 0)

	dao0610.DeleteBook(int(idInt))
	// 删除完之后再次查询显示列表
	GetBooks(w,r)
}

bookdao

/*
查:改前先回显
*/
func GetBookById(id string) (*model0610.Book, error) {
	sqlStr := "select id,title,author,price,sales,stock,img_path from books where id = ?"
	row := utils0610.Db.QueryRow(sqlStr, id)
	book := &model0610.Book{}
	err := row.Scan(&book.Id, &book.Title, &book.Author, &book.Price, &book.Sales, &book.Stock, &book.ImgPath)
	if err != nil {
		return nil, err
	}
	return book, nil
}

/*
改
*/
func UpdateBook(b *model0610.Book) error {
	//写sql语句
	sqlStr := "update books set title=?,author=?,price=?,sales=?,stock=? where id=?"
	//执行
	_, err := utils0610.Db.Exec(sqlStr, b.Title, b.Author, b.Price, b.Sales, b.Stock, b.Id)
	if err != nil {
		return err
	}
	return nil
}

bookController

/*
先查回显到表单,再改
 */
func GetBookById(w http.ResponseWriter,r *http.Request){
	idString := r.FormValue("bookId")
	book, _ := dao0610.GetBookById(idString)
	t := template.Must(template.ParseFiles("views/pages/manager/book_modify.html"))
	t.Execute(w,book)
}

/*
改图书
 */
func UpdateBookById(w http.ResponseWriter,r *http.Request){
	idString := r.PostFormValue("bookId")
	idInt, _ := strconv.ParseInt(idString, 10, 0)
	title := r.PostFormValue("title")
	author := r.PostFormValue("author")
	priceString := r.PostFormValue("price")
	priceFloat64, _ := strconv.ParseFloat(priceString, 64)
	salesString := r.PostFormValue("sales")
	salesInt, _ := strconv.ParseInt(salesString, 10, 0)
	stockString := r.PostFormValue("stock")
	stockInt, _ := strconv.ParseInt(stockString, 10, 0)
	imgPath := r.PostFormValue("imgPath")

	book := &model0610.Book{
		Id: int(idInt),
		Title: title,
		Author: author,
		Price: priceFloat64,
		Sales: int(salesInt),
		Stock: int(stockInt),
		ImgPath: imgPath,
	}
	dao0610.UpdateBook(book)
	GetBooks(w,r)
}

book_modify.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>修改图书</title>
<link type="text/css" rel="stylesheet" href="/static/css/style.css" >
<style type="text/css">
	h1 {
		text-align: center;
		margin-top: 200px;
	}
	
	h1 a {
		color:red;
	}
	
	input {
		text-align: center;
	}
</style>
</head>
<body>
		<div id="header">
			<img class="logo_img" alt="" src="/static/img/logo.gif" >
			<span class="wel_word">修改图书</span>
			<div>
				<a href="/pages/manager/book_manager.html">图书管理</a>
				<a href="/">返回商城</a>
			</div>
		</div>
		
		<div id="main">
			<form action="/updateBookById" method="POST">
<!--				这里必须设置隐藏域,否则将不知道更新谁,图书可能会重名的情况-->
				<input type="hidden" value="{{.Id}}" name="bookId"/>
				<table>
					<tr>
						<td>名称</td>
						<td>价格</td>
						<td>作者</td>
						<td>销量</td>
						<td>库存</td>
						<td colspan="2">操作</td>
					</tr>		
					<tr>
						<td><input name="title" type="text" value="{{.Title}}"/></td>
						<td><input name="price" type="text" value="{{.Price}}"/></td>
						<td><input name="author" type="text" value="{{.Author}}"/></td>
						<td><input name="sales" type="text" value="{{.Sales}}"/></td>
						<td><input name="stock" type="text" value="{{.Stock}}"/></td>
						<td><input type="submit" value="提交"/></td>
					</tr>		
				</table>
			</form>
		</div>
		
		<div id="bottom">
			<span>
				尚硅谷书城.Copyright &copy;2015
			</span>
		</div>
</body>
</html>

main.go

package main

import (
	"go_codes/day0610_cabbeen/controller0610"
	"html/template"
	"net/http"
)

/*
跳转首页,使用模板引擎
 */
func IndexHandler(w http.ResponseWriter,r *http.Request){
	t:=template.Must(template.ParseFiles("views/index.html"))
	t.Execute(w,"")
}

func main() {

	// 设置处理静态资源
	http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("views/static"))))
	// 直接通过a标签点击去往页面
	http.Handle("/pages/",http.StripPrefix("/pages/",http.FileServer(http.Dir("views/pages"))))
	http.HandleFunc("/index",IndexHandler)
	http.HandleFunc("/login",controller0610.Login)
	http.HandleFunc("/regist",controller0610.Regist)

	// ajax检查用户名是否被注册
	http.HandleFunc("/checkUsername",controller0610.CheckUsername)

	// 获取所有图书
	http.HandleFunc("/getBooks",controller0610.GetBooks)
	// 新增图书
	http.HandleFunc("/addBook",controller0610.AddBook)
	// 删除图书
	http.HandleFunc("/deleteBook",controller0610.DeleteBookById)
	// 回显给表单
	http.HandleFunc("/getBookById",controller0610.GetBookById)
	// 改图书
	http.HandleFunc("/updateBookById",controller0610.UpdateBookById)

	http.ListenAndServe(":8080",nil)
}
上一篇:mapengpeng1999@163.com RestFul风格CRUD,SpringMVC的表单标签


下一篇:C#---mysql的CRUD(基础)