Last active
February 3, 2021 17:40
-
-
Save krittawatcode/d8e4e08b1c06e5325987b5f6a1a8cce4 to your computer and use it in GitHub Desktop.
Pass gin.Context as context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package handler | |
import ( | |
"log" | |
"net/http" | |
"github.com/gin-gonic/gin" | |
"github.com/jacobsngoodwin/memrizr/account/model" | |
"github.com/jacobsngoodwin/memrizr/account/model/apperrors" | |
) | |
// signupReq is not exported, hence the lowercase name | |
// it is used for validation and json marshalling | |
type signupReq struct { | |
Email string `json:"email" binding:"required,email"` | |
Password string `json:"password" binding:"required,gte=6,lte=30"` | |
} | |
// Signup handler | |
func (h *Handler) Signup(c *gin.Context) { | |
// define a variable to which we'll bind incoming | |
// json body, {email, password} | |
var req signupReq | |
// Bind incoming json to struct and check for validation errors | |
if ok := bindData(c, &req); !ok { | |
return | |
} | |
u := &model.User{ | |
Email: req.Email, | |
Password: req.Password, | |
} | |
err := h.UserService.Signup(c, u) | |
if err != nil { | |
log.Printf("Failed to sign up user: %v\n", err.Error()) | |
c.JSON(apperrors.Status(err), gin.H{ | |
"error": err, | |
}) | |
return | |
} | |
c.JSON(http.StatusCreated, gin.H{ | |
"tokens": tokens, | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (s *UserService) Signup(ctx context.Context, u *model.User) error { | |
pw, err := hashPassword(u.Password) | |
if err != nil { | |
log.Printf("Unable to signup user for email: %v\n", u.Email) | |
return apperrors.NewInternal() | |
} | |
// now I realize why I originally used Signup(ctx, email, password) | |
// then created a user. It's somewhat un-natural to mutate the user here | |
u.Password = pw | |
if err := s.UserRepository.Create(ctx, u); err != nil { | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment