create post
This commit is contained in:
parent
fa5859e9fc
commit
9f27c64284
|
@ -5,7 +5,7 @@ import "gorm.io/gorm"
|
|||
//Wp_article Article model
|
||||
type Wp_article struct {
|
||||
gorm.Model // article_id, article_sendTime
|
||||
Id int `gorm:"column:article_type_id;type:int(11)"`
|
||||
Type int `gorm:"column:article_type_id;type:int(11)"`
|
||||
Title string `gorm:"column:article_title;type:varchar(40)"`
|
||||
Content string `gorm:"column:article_content;type:varchar(400)"`
|
||||
Source bool `gorm:"column:article_from;type:binary(1)"`
|
||||
|
|
|
@ -6,6 +6,7 @@ import (
|
|||
"GodPress/prjutil"
|
||||
"github.com/gin-contrib/gzip"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
|
@ -26,10 +27,10 @@ func InitRouter() *gin.Engine {
|
|||
|
||||
posts := api1.Group("posts") // Article-related APIs
|
||||
{
|
||||
posts.GET("/", ListPosts) // list posts
|
||||
posts.POST("/", CreatePost) // create a post
|
||||
posts.GET("/:id", RetrievePost) // retrieve a post
|
||||
posts.DELETE("/:id", DeletePost) // delete a post
|
||||
posts.GET("/", ListPosts) // list posts
|
||||
posts.POST("/", AuthorizeUser, CreatePost) // create a post
|
||||
posts.GET("/:id", RetrievePost) // retrieve a post
|
||||
posts.DELETE("/:id", DeletePost) // delete a post
|
||||
}
|
||||
|
||||
categories := api1.Group("categories") // Article type related APIs
|
||||
|
@ -93,3 +94,11 @@ func Ping(c *gin.Context) {
|
|||
"message": "pong",
|
||||
})
|
||||
}
|
||||
|
||||
// AuthorizeUser performs as a middleware to check if the user is authorized.
|
||||
func AuthorizeUser(c *gin.Context) {
|
||||
uid := prjutil.GetUserFromHeader(c)
|
||||
if uid == prjutil.NoActualUser {
|
||||
c.AbortWithStatus(http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,39 @@
|
|||
package posts
|
||||
|
||||
import (
|
||||
"GodPress/models"
|
||||
"GodPress/prjutil"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type CreatePostService struct {
|
||||
Content string `json:"content"`
|
||||
Source bool `json:"source"`
|
||||
Title string `json:"title"`
|
||||
Type int `json:"type"`
|
||||
}
|
||||
|
||||
func (s *CreatePostService) CreatePost(c *gin.Context) {
|
||||
author := prjutil.GetUserFromHeader(c)
|
||||
result := models.DB.Create(&models.Wp_article{
|
||||
Content: s.Content,
|
||||
Title: s.Title,
|
||||
Type: s.Type,
|
||||
Source: s.Source,
|
||||
Sender: int(author),
|
||||
LikeNum: 0,
|
||||
})
|
||||
if result.Error != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"code": 0,
|
||||
"message": result.Error.Error(),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"message": "已创建",
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue