You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.2 KiB

  1. package endpoint
  2. import (
  3. "github.com/fatih/color"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func fail(c *gin.Context, err error, msg string) {
  7. color.Red(msg + ": " + err.Error())
  8. c.JSON(400, gin.H{
  9. "error": msg,
  10. })
  11. }
  12. func handleMain(c *gin.Context) {
  13. c.JSON(200, gin.H{
  14. "status": "wellcome to gogame",
  15. })
  16. }
  17. func handleInfo(c *gin.Context) {
  18. c.JSON(200, gin.H{
  19. "info": "info",
  20. })
  21. }
  22. type RegisterMsg struct {
  23. Name string `binding:"required"`
  24. Password string `binding:"required"`
  25. Email string `binding:"required"`
  26. }
  27. func handleRegister(c *gin.Context) {
  28. var registerMsg RegisterMsg
  29. c.BindJSON(&registerMsg)
  30. user, err := userservice.Register(registerMsg.Name, registerMsg.Password, registerMsg.Email)
  31. if err != nil {
  32. fail(c, err, "error on register")
  33. return
  34. }
  35. c.JSON(200, gin.H{
  36. "user": user,
  37. })
  38. }
  39. type LoginMsg struct {
  40. Email string `binding:"required"`
  41. Password string `binding:"required"`
  42. }
  43. func handleLogin(c *gin.Context) {
  44. var loginMsg LoginMsg
  45. c.BindJSON(&loginMsg)
  46. token, user, err := userservice.Login(loginMsg.Email, loginMsg.Password)
  47. if err != nil {
  48. fail(c, err, "error on login")
  49. return
  50. }
  51. c.JSON(200, gin.H{
  52. "token": token,
  53. "user": user,
  54. })
  55. }