Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commita79e553

Browse files
committed
updated
1 parent4631b94 commita79e553

File tree

9 files changed

+185
-27
lines changed

9 files changed

+185
-27
lines changed

‎controllers/auth.controller.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ func (ac *AuthController) SignUpUser(ctx *gin.Context) {
5757
result:=ac.DB.Create(&newUser)
5858

5959
ifresult.Error!=nil {
60+
ifstrings.Contains(result.Error.Error(),"duplicate key") {
61+
ctx.JSON(http.StatusConflict, gin.H{"status":"fail","message":"User with that email already exists"})
62+
return
63+
}
6064
ctx.JSON(http.StatusBadGateway, gin.H{"status":"error","message":"Something bad happened"})
6165
return
6266
}

‎controllers/post.controller.go

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
package controllers
2+
3+
import (
4+
"net/http"
5+
"strconv"
6+
"strings"
7+
"time"
8+
9+
"github.com/gin-gonic/gin"
10+
"github.com/wpcodevo/golang-gorm-postgres/models"
11+
"gorm.io/gorm"
12+
)
13+
14+
typePostControllerstruct {
15+
DB*gorm.DB
16+
}
17+
18+
funcNewPostController(DB*gorm.DB)PostController {
19+
returnPostController{DB}
20+
}
21+
22+
func (pc*PostController)CreatePost(ctx*gin.Context) {
23+
currentUser:=ctx.MustGet("currentUser").(models.User)
24+
varpayload*models.CreatePostRequest
25+
26+
iferr:=ctx.ShouldBindJSON(&payload);err!=nil {
27+
ctx.JSON(http.StatusBadRequest,err.Error())
28+
return
29+
}
30+
31+
now:=time.Now()
32+
newPost:= models.Post{
33+
Title:payload.Title,
34+
Content:payload.Content,
35+
Image:payload.Image,
36+
User:currentUser.ID,
37+
CreatedAt:now,
38+
UpdatedAt:now,
39+
}
40+
41+
result:=pc.DB.Create(&newPost)
42+
ifresult.Error!=nil {
43+
ifstrings.Contains(result.Error.Error(),"duplicate key") {
44+
ctx.JSON(http.StatusConflict, gin.H{"status":"fail","message":"Post with that title already exists"})
45+
return
46+
}
47+
ctx.JSON(http.StatusBadGateway, gin.H{"status":"error","message":result.Error.Error()})
48+
return
49+
}
50+
51+
ctx.JSON(http.StatusCreated, gin.H{"status":"success","data":newPost})
52+
}
53+
54+
func (pc*PostController)UpdatePost(ctx*gin.Context) {
55+
postId:=ctx.Param("postId")
56+
currentUser:=ctx.MustGet("currentUser").(models.User)
57+
58+
varpayload*models.UpdatePost
59+
iferr:=ctx.ShouldBindJSON(&payload);err!=nil {
60+
ctx.JSON(http.StatusBadGateway, gin.H{"status":"fail","message":err.Error()})
61+
return
62+
}
63+
varupdatedPost models.Post
64+
result:=pc.DB.First(&updatedPost,"id = ?",postId)
65+
ifresult.Error!=nil {
66+
ctx.JSON(http.StatusNotFound, gin.H{"status":"fail","message":"No post with that title exists"})
67+
return
68+
}
69+
now:=time.Now()
70+
postToUpdate:= models.Post{
71+
Title:payload.Title,
72+
Content:payload.Content,
73+
Image:payload.Image,
74+
User:currentUser.ID,
75+
CreatedAt:updatedPost.CreatedAt,
76+
UpdatedAt:now,
77+
}
78+
79+
pc.DB.Model(&updatedPost).Updates(postToUpdate)
80+
81+
ctx.JSON(http.StatusOK, gin.H{"status":"success","data":updatedPost})
82+
}
83+
84+
func (pc*PostController)FindPostById(ctx*gin.Context) {
85+
postId:=ctx.Param("postId")
86+
87+
varpost models.Post
88+
result:=pc.DB.First(&post,"id = ?",postId)
89+
ifresult.Error!=nil {
90+
ctx.JSON(http.StatusNotFound, gin.H{"status":"fail","message":"No post with that title exists"})
91+
return
92+
}
93+
94+
ctx.JSON(http.StatusOK, gin.H{"status":"success","data":post})
95+
}
96+
97+
func (pc*PostController)FindPosts(ctx*gin.Context) {
98+
varpage=ctx.DefaultQuery("page","1")
99+
varlimit=ctx.DefaultQuery("limit","10")
100+
101+
intPage,_:=strconv.Atoi(page)
102+
intLimit,_:=strconv.Atoi(limit)
103+
offset:= (intPage-1)*intLimit
104+
105+
varposts []models.Post
106+
results:=pc.DB.Limit(intLimit).Offset(offset).Find(&posts)
107+
ifresults.Error!=nil {
108+
ctx.JSON(http.StatusBadGateway, gin.H{"status":"error","message":results.Error})
109+
return
110+
}
111+
112+
ctx.JSON(http.StatusOK, gin.H{"status":"success","results":len(posts),"data":posts})
113+
}
114+
115+
func (pc*PostController)DeletePost(ctx*gin.Context) {
116+
postId:=ctx.Param("postId")
117+
118+
result:=pc.DB.Delete(&models.Post{},"id = ?",postId)
119+
120+
ifresult.Error!=nil {
121+
ctx.JSON(http.StatusNotFound, gin.H{"status":"fail","message":"No post with that title exists"})
122+
return
123+
}
124+
125+
ctx.JSON(http.StatusNoContent,nil)
126+
}

‎main.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ var (
1818

1919
UserController controllers.UserController
2020
UserRouteController routes.UserRouteController
21+
22+
PostController controllers.PostController
23+
PostRouteController routes.PostRouteController
2124
)
2225

2326
funcinit() {
@@ -34,6 +37,9 @@ func init() {
3437
UserController=controllers.NewUserController(initializers.DB)
3538
UserRouteController=routes.NewRouteUserController(UserController)
3639

40+
PostController=controllers.NewPostController(initializers.DB)
41+
PostRouteController=routes.NewRoutePostController(PostController)
42+
3743
server=gin.Default()
3844
}
3945

@@ -57,5 +63,6 @@ func main() {
5763

5864
AuthRouteController.AuthRoute(router)
5965
UserRouteController.UserRoute(router)
66+
PostRouteController.PostRoute(router)
6067
log.Fatal(server.Run(":"+config.ServerPort))
6168
}

‎migrate/migrate.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,6 @@ func init() {
1818
}
1919

2020
funcmain() {
21-
initializers.DB.AutoMigrate(&models.User{})
21+
initializers.DB.AutoMigrate(&models.User{},&models.Post{})
2222
fmt.Println("👍 Migration complete")
2323
}

‎models/post.model.go

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,30 +7,29 @@ import (
77
)
88

99
typePoststruct {
10-
ID uuid.UUID`gorm:"type:uuid;default:uuid_generate_v4();primary_key"`
11-
Titlestring``
12-
Contentstring``
13-
Imagestring``
14-
Userstring``
15-
CreateAttime.Time``
16-
UpdatedAt time.Time``
10+
ID uuid.UUID`gorm:"type:uuid;default:uuid_generate_v4();primary_key" json:"id,omitempty"`
11+
Titlestring`gorm:"uniqueIndex;not null" json:"title,omitempty"`
12+
Contentstring`gorm:"not null" json:"content,omitempty"`
13+
Imagestring`gorm:"not null" json:"image,omitempty"`
14+
Useruuid.UUID`gorm:"not null" json:"user,omitempty"`
15+
CreatedAttime.Time`gorm:"not null" json:"created_at,omitempty"`
16+
UpdatedAt time.Time`gorm:"not null" json:"updated_at,omitempty"`
1717
}
1818

1919
typeCreatePostRequeststruct {
20-
Titlestring`json:"title"bson:"title" binding:"required"`
21-
Contentstring`json:"content"bson:"content"binding:"required"`
22-
Imagestring`json:"image,omitempty" bson:"image,omitempty"`
23-
Userstring`json:"user" bson:"user" binding:"required"`
24-
CreateAttime.Time`json:"created_at,omitempty" bson:"created_at,omitempty"`
25-
UpdatedAt time.Time`json:"updated_at,omitempty" bson:"updated_at,omitempty"`
20+
Titlestring`json:"title" binding:"required"`
21+
Contentstring`json:"content" binding:"required"`
22+
Imagestring`json:"image" binding:"required"`
23+
Userstring`json:"user,omitempty"`
24+
CreatedAttime.Time`json:"created_at,omitempty"`
25+
UpdatedAt time.Time`json:"updated_at,omitempty"`
2626
}
2727

2828
typeUpdatePoststruct {
29-
ID uuid.UUID`gorm:"type:uuid;default:uuid_generate_v4();primary_key"`
30-
Titlestring`json:"title,omitempty" bson:"title,omitempty"`
31-
Contentstring`json:"content,omitempty" bson:"content,omitempty"`
32-
Imagestring`json:"image,omitempty" bson:"image,omitempty"`
33-
Userstring`json:"user,omitempty" bson:"user,omitempty"`
34-
CreateAt time.Time`json:"created_at,omitempty" bson:"created_at,omitempty"`
35-
UpdatedAt time.Time`json:"updated_at,omitempty" bson:"updated_at,omitempty"`
29+
Titlestring`json:"title,omitempty"`
30+
Contentstring`json:"content,omitempty"`
31+
Imagestring`json:"image,omitempty"`
32+
Userstring`json:"user,omitempty"`
33+
CreateAt time.Time`json:"created_at,omitempty"`
34+
UpdatedAt time.Time`json:"updated_at,omitempty"`
3635
}

‎models/user.model.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,6 @@ type User struct {
1919
UpdatedAt time.Time`gorm:"not null"`
2020
}
2121

22-
func (User)UsersTable()string {
23-
return"users"
24-
}
25-
2622
typeSignUpInputstruct {
2723
Namestring`json:"name" binding:"required"`
2824
Emailstring`json:"email" binding:"required"`

‎routes/auth.routes.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ func NewAuthRouteController(authController controllers.AuthController) AuthRoute
1515
}
1616

1717
func (rc*AuthRouteController)AuthRoute(rg*gin.RouterGroup) {
18-
router:=rg.Group("/auth")
18+
router:=rg.Group("auth")
1919

2020
router.POST("/register",rc.authController.SignUpUser)
2121
router.POST("/login",rc.authController.SignInUser)

‎routes/post.routes.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package routes
2+
3+
import (
4+
"github.com/gin-gonic/gin"
5+
"github.com/wpcodevo/golang-gorm-postgres/controllers"
6+
"github.com/wpcodevo/golang-gorm-postgres/middleware"
7+
)
8+
9+
typePostRouteControllerstruct {
10+
postController controllers.PostController
11+
}
12+
13+
funcNewRoutePostController(postController controllers.PostController)PostRouteController {
14+
returnPostRouteController{postController}
15+
}
16+
17+
func (pc*PostRouteController)PostRoute(rg*gin.RouterGroup) {
18+
19+
router:=rg.Group("posts")
20+
router.Use(middleware.DeserializeUser())
21+
router.POST("/",pc.postController.CreatePost)
22+
router.GET("/",pc.postController.FindPosts)
23+
router.PUT("/:postId",pc.postController.UpdatePost)
24+
router.GET("/:postId",pc.postController.FindPostById)
25+
router.DELETE("/:postId",pc.postController.DeletePost)
26+
}

‎tmp/build-errors.log

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
exit status 0xc000013aexit status 2exit status 1exit status 1exit status 1exit status 2exit status1
1+
exit status 0xc000013aexit status 2exit status 1exit status 1exit status 1exit status 2exit status1exit status 0xc000013aexit status 2

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp