|- 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
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.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)
}
在数据库中查看:
https://getbootstrap.com/
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>Documenttitle>
head>
<body>
<div class="container">
<nav class="navbar" style="background-color: #e3f2fd;">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbara>
<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="