### GoWeb开发实战Gin框架】微博项目实战\_项目介绍和项目搭建
# 项目实战
## 一、项目介绍
从今天开始我们着手写一个项目。虽然规模不大,但是可以融入之前学习的很多内容。这个项目还是之前在讲《GoWeb开发实战(Beego框架实现项目)》中的项目。
在项目中,需要涉及到MVC的三个层面,包括view,controller,还有model。所以无论是页面,还是数据库,我们都需要自己一行一行实现。
> 本人不是专业设计人员,所以页面可能不太美。。
运行效果:
运行项目后,在浏览器中输入网址:[http://127.0.0.1:8081/](http://127.0.0.1:8081/)
直接进入首页:

## 二、项目搭建
首先打开Goland开发工具,新建一个项目,名称叫:blogweb\_gin,然后新建以下目录:

执行原理:
* 1. 进入main.go,初始化路由,以及端口号
* 2. 根据浏览器输入的URL地址,在router路由器中找到对应的路由函数方法
* 3. 根据路由中URL后指定的函数,在Controller中找到对应的方法函数
* 4. Controller中调用models关于数据库方面的方法函数
* 5. 渲染html页面,执行js,css等效果
首先我们在routers目录下,新建go文件:router.go
~~~go
package routers
import (
"github.com/gin-gonic/gin"
"blogweb_gin/controllers"
)
func InitRouter() *gin.Engine {
router := gin.Default()
router.LoadHTMLGlob("views/*")
//注册:
router.GET("/register",controllers.RegisterGet)
return router
}
~~~
接下来在controllers目录下新建go文件register\_controller.go:
~~~go
package controllers
import (
"github.com/gin-gonic/gin"
"net/http"
)
func RegisterGet(c *gin.Context) {
//返回html
c.HTML(http.StatusOK,"register.html",gin.H{"title":"注册页"})
}
~~~
然后在views目录下,新建一个html页面register.html:
~~~html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
<link rel="stylesheet" type="text/css" href="/static/css/lib/login.css">
<link rel="stylesheet" type="text/css" href="/static/css/blogsheet.css">
<script src="/static/js/lib/jquery-3.3.1.min.js"></script>
<script src="/static/js/lib/jquery.url.js"></script>
<script src="/static/js/blog.js"></script>
</head>
<body>
<div id="nav">
<div id="nav-login">
<ul>
<li><a href="/login">登录</a></li>
<li><a href="/register">注册</a></li>
</ul>
</div>
</div>
<div class="htmleaf-container">
<div class="wrapper">
<!--注册表单-->
<div class="container">
<h1>Welcome</h1>
<form id="register-form" class="form">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password" id="register-password">
<input type="password" name="repassword" placeholder="rePassword">
<br>
<button type="submit" id="login-button">Register</button>
</form>
</div>
<!--背景动画-->
<ul class="bg-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</body>
</html>
~~~
然后在main.go,主程序中:
~~~go
package main
import (
_ "myblogweb/routers"
"blogweb_gin/routers"
)
func main() {
router := routers.InitRouter()
//静态资源
router.Static("/static", "./static")
router.Run(":8081")
}
~~~
然后右键运行项目,打开浏览器输入以下网址:[http://127.0.0.1:8081/register](http://127.0.0.1:8081/register)
