文章目录
一 项目结构
规范包和目录
|- controller // gin相关处理函数
|- dao // 数据库访问
|- router // 路由
|- model // 生成数据库的结构体
|- assets // 静态资源
|- templates // 模板文件
初始化项目
go mod init blog
导包测试:
controller\controller.go:
package controller
import "fmt"
func TestController() {
fmt.Println("test...")
}
main.go:
package main
import "blog/controller"
func main() {
controller.TestController()
}
运行结果:
[Running] go run "c:\Users\Mechrevo\Desktop\golang笔记\golang web开发\blog\main.go"
test...
[Done] exited with code=0 in 1.935 seconds
二 集成gorm
下载包
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
创建模型
model\model.go:
package model
import "gorm.io/gorm"
type User struct {
gorm.Model
Username string `json:"username"`
Password string `json:"passowrd"`
}
创建Dao
dao\dao.go:
package dao
import (
"blog/model"
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Manager interface {
AddUser(user *model.User)
}
type manager struct {
db *gorm.DB
}
var Mgr Manager
func init() {
dsn := "root:960690@tcp(127.0.0.1:3306)/golang_db?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
})
if err != nil {
log.Fatal("Failed to init db:", err)
}
Mgr = &manager{
db: db}
db.AutoMigrate(&model.User{
})
}
func (mgr *manager) AddUser(user *model.User) {
mgr.db.Create(user)
}
测试
main.go:
package main
import (
"blog/dao"
"blog/model"
)
func main() {
user := model.User{
Username: "Psych",
Password: "123",
}
dao.Mgr.AddUser(&user)
}
在数据库中查看:
三 集成BootStrap创建用户表单
下载bootstrap
https://getbootstrap.com/
添加js和css到assets目录下面
创建添加用户html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/assets/css/bootstrap.min.css">
<script src="/assets/js/bootstrap.min.js"></script>
<title>Document</title>
</head>
<body>
<div class="container">
<nav class="navbar" style="background-color: #e3f2fd;">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent