123 lines
2.5 KiB
Go
123 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"go_blog/conf"
|
|
"go_blog/controllers"
|
|
"go_blog/models"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type User struct {
|
|
Name string
|
|
Gender string
|
|
Age int
|
|
Password string
|
|
PasswordHash []byte
|
|
}
|
|
|
|
var host string
|
|
var port string
|
|
var isDebugMode bool
|
|
var isErrMsg bool
|
|
var isOrmDebug bool
|
|
|
|
const templatePath = "./templates/*"
|
|
|
|
func init() {
|
|
flag.StringVar(&host, "h", "127.0.0.1", "主机")
|
|
flag.StringVar(&port, "p", "", "监听端口")
|
|
flag.BoolVar(&isDebugMode, "debug", true, "是否开启debug")
|
|
flag.BoolVar(&isErrMsg, "err", true, "是否返回错误信息")
|
|
flag.BoolVar(&isOrmDebug, "orm", true, "是否开启gorm的debug信息")
|
|
flag.Parse()
|
|
|
|
<<<<<<< HEAD
|
|
//conf.SetUp()
|
|
conf.SetUp1()
|
|
=======
|
|
conf.SetUp()
|
|
>>>>>>> c628419559368f0270c2573d91a06a1a9531d53a
|
|
models.SetUp(isOrmDebug)
|
|
}
|
|
|
|
func main() {
|
|
r := gin.Default()
|
|
|
|
r.LoadHTMLGlob(templatePath)
|
|
// 注册WebSocket路由
|
|
registerRoutes(r)
|
|
r.GET("/events", esSSE)
|
|
r.Run(":8080")
|
|
}
|
|
func esSSE(c *gin.Context) {
|
|
w := c.Writer
|
|
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
w.Header().Set("Connection", "keep-alive")
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
_, ok := w.(http.Flusher)
|
|
|
|
if !ok {
|
|
log.Panic("server not support") //浏览器不兼容
|
|
}
|
|
|
|
_, err := fmt.Fprintf(w, "data: %s\n\n", "dsdf")
|
|
if err != nil {
|
|
return
|
|
}
|
|
}
|
|
|
|
func registerRoutes(r *gin.Engine) {
|
|
|
|
var items []models.Content
|
|
models.DB.Select("*").Limit(5).Find(&items, "type = ?", "post")
|
|
r.GET("/", func(c *gin.Context) {
|
|
c.HTML(http.StatusOK, "index.tmpl", gin.H{
|
|
"Items": items,
|
|
})
|
|
})
|
|
r.GET("/createcontent", func(c *gin.Context) {
|
|
c.HTML(http.StatusOK, "content.tmpl", nil)
|
|
})
|
|
|
|
r.GET("/post/:id", func(c *gin.Context) {
|
|
id, err := strconv.ParseInt(c.Param("id"), 10, 32)
|
|
if err != nil {
|
|
return
|
|
}
|
|
var content = models.Content{Cid: int32(id)}
|
|
models.DB.First(&content)
|
|
c.HTML(http.StatusOK, "post.tmpl", content)
|
|
})
|
|
user := getUserInfo()
|
|
r.GET("/login", func(c *gin.Context) {
|
|
c.HTML(200, "login.tmpl", map[string]interface{}{
|
|
"title": "这个是titile,传入templates中的",
|
|
"user": user,
|
|
})
|
|
})
|
|
|
|
r.GET("/ws", controllers.WebSocketHandler)
|
|
r.POST("/content", controllers.CreateContentHandler)
|
|
r.POST("/login", controllers.UsersLoginHandler)
|
|
}
|
|
|
|
func getUserInfo() User {
|
|
user := User{
|
|
Name: "user",
|
|
Gender: "male",
|
|
Age: 18,
|
|
Password: "nothings",
|
|
PasswordHash: []byte("nothings"),
|
|
}
|
|
return user
|
|
}
|