Skip to content

Instantly share code, notes, and snippets.

@Cibernomadas
Created July 4, 2018 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cibernomadas/e3cee2a730c451bdf8ecfdd677a3f990 to your computer and use it in GitHub Desktop.
Save Cibernomadas/e3cee2a730c451bdf8ecfdd677a3f990 to your computer and use it in GitHub Desktop.
func EditProfileFn(c *gin.Context) {
currentUser := models.User{}
session := sessions.Default(c)
u := session.Get("user")
if u != nil {
currentUser = u.(models.User)
}
dbc, exist := c.Get("db")
if !exist {
c.HTML(http.StatusOK, "index", gin.H{
"title": "Hi! GoBlog.",
"error": "We've got an internal error, please try later.",
})
return
}
if c.Request.Method == http.MethodGet { // Edit profile form
c.HTML(http.StatusOK, "edit_profile", gin.H{
"title": "Hi! GoBlog.",
"user": currentUser,
})
} else if c.Request.Method == http.MethodPost { // Process profile form
var profileForm models.EditProfile
if err := c.ShouldBind(&profileForm); err == nil {
db := dbc.(*gorm.DB)
var errors string
var user models.User
db.Where("username = ?", profileForm.Username).First(&user)
if db.NewRecord(user) { // If true no user found
currentUser.Username = profileForm.Username
currentUser.AboutMe = profileForm.AboutMe
db.Save(&currentUser)
session.Set("user", currentUser)
session.Save()
} else {
errors = "User name in use, plase choose another one."
}
posts := [...]struct {
Author *models.User
Body string
}{
{&currentUser, "Test post #1"},
{&currentUser, "Test post #2"},
}
c.HTML(http.StatusOK, "profile", gin.H{
"title": "Hi! GoBlog.",
"user": &currentUser,
"current_user": &currentUser,
"posts": posts,
"error": errors,
})
} else {
c.HTML(http.StatusOK, "edit_profile", gin.H{
"title": "Hi! GoBlog.",
"error": "Required fields are not provided correctly.",
})
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment