Last active
July 3, 2023 10:59
-
-
Save manakuro/98b6e3cc31df5a8072d508abfbda6bfd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import ( | |
... | |
rc "firebase-authentication-with-react-and-go/backend/router/context" | |
m "firebase-authentication-with-react-and-go/backend/router/middleware" | |
) | |
func main() { | |
// ... | |
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ | |
AllowOrigins: []string{"*"}, | |
AllowMethods: []string{http.MethodGet, http.MethodPost, http.MethodOptions}, | |
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderXRequestedWith, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAuthorization}, | |
})) | |
//--- restricted api ---// | |
g := e.Group("api", m.Auth()) | |
g.POST("/users", wrapCustomContext(func(c *rc.Context) error { | |
var params model.User | |
user := model.User{} | |
if err := c.Bind(¶ms); !errors.Is(err, nil) { | |
return c.JSON(http.StatusBadRequest, err.Error()) | |
} | |
// Check to see if the user already registered | |
err = db.Where(&model.User{UUID: params.UUID}).First(&user).Error | |
if !errors.Is(err, nil) && !gorm.IsRecordNotFoundError(err) { | |
return c.JSON(http.StatusBadRequest, err.Error()) | |
} | |
if user.UUID != "" { | |
return c.JSON(http.StatusBadRequest, "The user already registered") | |
} | |
// Create a new user when not registered | |
user = params | |
err = db.Create(&user).Error | |
if !errors.Is(err, nil) { | |
return err | |
} | |
return c.JSON(http.StatusCreated, user) | |
})) | |
// ... | |
} | |
func wrapCustomContext(fn func(c *rc.Context) error) echo.HandlerFunc { | |
return func(ctx echo.Context) error { | |
return fn(ctx.(*rc.Context)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment