{"id":26241154,"url":"https://github.com/solrac97gr/go-jwt-auth","last_synced_at":"2025-04-23T04:37:46.030Z","repository":{"id":62916728,"uuid":"563532282","full_name":"solrac97gr/go-jwt-auth","owner":"solrac97gr","description":"Template create for use as CookieCutter for my Golang projects, I decided to create a template with everything already working. 🚀","archived":false,"fork":false,"pushed_at":"2023-08-29T11:01:35.000Z","size":121,"stargazers_count":99,"open_issues_count":4,"forks_count":14,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-04-18T12:53:09.014Z","etag":null,"topics":["cookiecutter","go","golang","jwt","mongodb"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/solrac97gr.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-11-08T20:09:13.000Z","updated_at":"2025-03-15T23:21:35.000Z","dependencies_parsed_at":"2024-06-20T05:40:27.442Z","dependency_job_id":"d8f25b38-c6a8-4285-8804-b24b8e73de84","html_url":"https://github.com/solrac97gr/go-jwt-auth","commit_stats":null,"previous_names":[],"tags_count":0,"template":true,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/solrac97gr%2Fgo-jwt-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/solrac97gr%2Fgo-jwt-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/solrac97gr%2Fgo-jwt-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/solrac97gr%2Fgo-jwt-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/solrac97gr","download_url":"https://codeload.github.com/solrac97gr/go-jwt-auth/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250372628,"owners_count":21419719,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cookiecutter","go","golang","jwt","mongodb"],"created_at":"2025-03-13T08:19:39.365Z","updated_at":"2025-04-23T04:37:46.000Z","avatar_url":"https://github.com/solrac97gr.png","language":"Go","funding_links":["https://www.buymeacoffee.com/carlosgarcA"],"categories":[],"sub_categories":[],"readme":"# Go JWT Auth (Fiber \u0026 Mongo)\n\n\u003ca href=\"https://www.buymeacoffee.com/carlosgarcA\" target=\"_blank\"\u003e\u003cimg src=\"https://cdn.buymeacoffee.com/buttons/v2/arial-yellow.png\" alt=\"Buy Me A Coffee\" style=\"height: 60px !important;width: 217px !important;\" \u003e\u003c/a\u003e\n\nTemplate create for use as CookieCutter for my Golang projects. \nThe hardest part for start a project for me was to chose Stack and create the initial login and integrations\nlike logger, database, etc. So I decided to create a template with everything already working.\n\nAll the project is based in interfaces that mean you can implement your own logic and use it in the project.\nexample: you can use different database like Postgres, MySQL, etc. Just implement the interface and use it.\n\n## Stack\n- Router: [Fiber 🚀](https://gofiber.io)\n- Database: [Mongo 💾](https://www.mongodb.com/docs/drivers/go/current/) \n- Doc: [Swagger 📄](https://github.com/swaggo/swag)\n- Logger: [Zap ⚡](https://github.com/uber-go/zap)\n- Mocks: [gomock 💀](https://github.com/uber-go/mock)\n- Deploy: [Docker 🐳](https://www.docker.com)\n- CI: [Github Actions 🐙](https://docs.github.com/en/actions)\n\n## Before the execution\n- Modify the file `./config/env.json` with your parameters\n- Install gomock `go install go.uber.org/mock/mockgen@latest`\n- Install swag `go install github.com/swaggo/swag/cmd/swag@latest`\n\n## Routes\nYou can also check in the route /swagger/index.html after run the project 🤩.\n\nNote 📝: For add a private route you need to create it in the private router `v1Private`\ninside the pkg/server/server.go file.\n\n| Name          | Path             | Method | Description          | Request        | Response |\n|---------------|------------------|--------|----------------------|----------------|----------|\n| Register      | /api/v1/register | POST   | Create a new user    | email,password |          |\n| Login         | /api/v1/login    | POST   | Login a user         | email,password | token    |\n| Metrics       | /metrics         | GET    | Monitor for your API |                | html     |\n| Documentation | /docs            | GET    | Documentation        |                | html     |\n\n## How to use\nFor this example we will make suppose that you want to create endpoints for Blog Posts.\n1. Create a new folder inside the internal folder with the name of your entity. In this case `post`.\n2. Create tree folders inside the entity folder: `application`, `domain` and `infrastructure`.\n3. Create two folders inside the domain folder: `ports` and `model`.\n4. Create a file inside the model folder with the name of your entity. In this case `post.go` and define your struct `Post`.\n    ```go\n    package model\n   \n   import \"time\"  \n\n    type Post struct {\n        ID        string `json:\"id\" bson:\"_id\"`\n        Title     string             `json:\"title\" bson:\"title\"`\n        Content   string             `json:\"content\" bson:\"content\"`\n        CreatedAt time.Time          `json:\"created_at\" bson:\"created_at\"`\n        UpdatedAt time.Time          `json:\"updated_at\" bson:\"updated_at\"`\n    }\n    ```\n\n5. Create 3 files inside the ports folder: `repository.go`, `handlers.go` and `application.go`.\n6. Define your interfaces inside the `repository.go`,`handlers.go` and `application.go` file.\n   ```go\n   package ports\n   \n   import \"github.com/your_user/your_project/internal/post/domain/model\"\n   \n   type PostRepository interface {\n        Create(post *model.Post) error\n        FindAll() ([]*model.Post, error)\n        FindByID(id string) (*model.Post, error)\n        Update(post *model.Post) error\n        Delete(id string) error\n    }\n    ```\n7. Modify the `scripts/generate-mocks.sh` file and add your three new interfaces.\n   ```sh\n   mockgen -destination=pkg/mocks/mock_post_application.go -package=mocks --build_flags=--mod=mod github.com/solrac97gr/go-jwt-auth/internal/post/domain/ports PostApplication \u0026\u0026\n   mockgen -destination=pkg/mocks/mock_post_repository.go -package=mocks --build_flags=--mod=mod github.com/solrac97gr/go-jwt-auth/internal/post/domain/ports PostRepository \u0026\u0026\n   mockgen -destination=pkg/mocks/mock_post_handlers.go -package=mocks --build_flags=--mod=mod github.com/solrac97gr/go-jwt-auth/internal/post/domain/ports PostHandlers\n   ```\n8. Run the `scripts/generate-mocks.sh` file.\n9. Now is time for implement your interfaces. Create two folders inside the `infrastructure` folder with the name of `repositories` and `handlers`.\n10. Create a file inside the `repositories` folder with the name of your interface implementation. In this case `mongo.go` and implement the `PostRepository` interface.\n   ```go\n    package repositories\n\n    type MongoPostRepository struct {\n        db *mongo.Database\n        logger logger.LoggerApplication\n        configurator config.ConfigApplication\n    }\n    \n    func NewMongoPostRepository(db *mongo.Database) *MongoPostRepository {\n        return \u0026MongoPostRepository{db: db}\n    }\n\n    func (m *MongoPostRepository) Create(post *model.Post) error {\n        _, err := m.db.Collection(\"posts\").InsertOne(context.Background(), post)\n        if err != nil {\n\t\t\tm.logger.Error(\"Error creating post\", err)\n            return err\n        }\n        return nil\n    }\n    .\n    .\n    .\n   ```\n11. Create a file inside the `handlers` folder with the name of your interface implementation. In this case `http.go` and implement the `PostHandler` interface.\n   ```go\n   package handlers\n\n    type HTTPPostHandler struct {\n        postApplication ports.PostApplication\n        logger logger.LoggerApplication\n        validator validator.ValidatorApplication\n    }\n    \n    func NewHTTPPostHandler(postApplication ports.PostApplication) *HTTPPostHandler {\n        return \u0026HTTPPostHandler{postApplication: postApplication}\n    }\n\n    func (h *HTTPPostHandler) CreatePost(c *fiber.Ctx) error {\n        post := \u0026model.Post{}\n        if err := c.BodyParser(post); err != nil {\n            h.logger.Error(\"Error parsing post\", err)\n            return c.Status(http.StatusBadRequest).JSON(fiber.Map{\"error\": err.Error()})\n        }\n        if err := h.postApplication.Create(post); err != nil {\n            h.logger.Error(\"Error creating post\", err)\n            return c.Status(http.StatusInternalServerError).JSON(fiber.Map{\"error\": err.Error()})\n        }\n        return c.Status(http.StatusCreated).JSON(fiber.Map{\"message\": \"Post created successfully\"})\n    }\n    .\n    .\n    .\n   ```\n12. Add your handlers to new routes depends on if it's public or private. In this case we will add it to the private routes in file `pkg/server/server.go` .\n   ```go\n   v1Private.Post(\"/posts\", h.postHandler.CreatePost)\n   ```\n13. If you want to add it to the swagger documentation view use comment with special annotation for your handlers.\n   ```go\n   // @Summary Create a new post\n   // @Description Create a new post\n   // @Tags posts\n   // @Accept json\n   // @Produce json\n   // @Param post body model.Post true \"Post\"\n   // @Success 201 {object} fiber.Map\n   // @Failure 400 {object} fiber.Map\n   // @Failure 500 {object} fiber.Map\n   // @Router /posts [post]\n   func (h *HTTPPostHandler) CreatePost(c *fiber.Ctx) error {\n        .\n        .\n        .\n   }\n   ```\n14. Generate the swagger documentation with the command `/scripts/generate-docs.sh`.\n15. Run the project with the command `go run cmd/http/main.go` or with the script `scripts/run.sh`.\n\n## Considerations\n- The `scripts/generate-mocks.sh` file is used to generate the mocks of the interfaces.\n- The `scripts/generate-docs.sh` file is used to generate the swagger documentation.\n- The `scripts/run.sh` file is used to run the project.\n- The `scripts/run-tests.sh` file is used to run the tests.\n- The `scripts/run-tests-coverage.sh` file is used to run the tests with coverage.\n- For avoid create users with same mail, make the mail field unique in the database (mongo index in this case).\n\n## License\n[Apache License 2.0]()\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsolrac97gr%2Fgo-jwt-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsolrac97gr%2Fgo-jwt-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsolrac97gr%2Fgo-jwt-auth/lists"}