DEV Community

Discussion on: Create a Restful API with Golang from scratch

Collapse
 
pacheco profile image
Thiago Pacheco • Edited

Hi Matej, thanks a lot for your feedback! I am glad you liked it.
Given your explanation above, I would actually suggest you to start by mapping your concepts into models like the todo model example. From there you create the repositories and handlers accordingly.
It is a bit hard to help without knowing much about your context, but I would gladly provide more help if you'd share more details about it. You can DM me on twitter if you want: @dev_pacheco.

Collapse
 
mathmul profile image
Matej

I really would take you up on the offer, but @dev_pacheco can't be messaged.

I did make a copy of "todo" folder (module) and renamed it to "group". Also renamed everything in the files from todo to group, Todo to Group, and TodoSomething to GroupSomething. This wouldn't immediately be OK, since Group was wrong, given my import "github.com/me/project/gen/models", so I had to replace Todo with models.Group, and most errors were gone. It also automatically put an asterisk (*) before group.Name in func (repository) Find (id) in the if condition. Then I suppose I can just delete the "models.go" file in "groups" module. So now I think all it's left is to fix Register func to have the same basePath as in REST API, ie.

func Register(router fiber.Router, database *gorm.DB) {
    database.AutoMigrate(&models.Group{})
    groupRepository := NewGroupRepository(database)
    groupHandler := NewGroupHandler(groupRepository)

    groupsRouter := router.Group("/groups")
    groupsRouter.Get("/", groupHandler.GetAll)
    groupsRouter.Post("/", groupHandler.Create)
    groupsRouter.Get("/:id", groupHandler.Get)
    groupsRouter.Put("/:id", groupHandler.Update)
    groupsRouter.Delete("/:id", groupHandler.Delete)
}
Enter fullscreen mode Exit fullscreen mode

And yes that actually worked! Thank you... I am curious though if I really need to set Router stuff here in the register manually like this, or can I get those methods set somehow from the REST API files generated from Swagger?

Thread Thread
 
mathmul profile image
Matej

Also how does one write tests to make sure the database is connected, or a new Todo can be added?

Thread Thread
 
pacheco profile image
Thiago Pacheco

Hey Matej, I am glad you could figure it out!
About the router, you can definitely setup differently, the Register func is just a suggestion. The idea about having this Register func is to have an unique way to initialize each of your modules.

Thread Thread
 
pacheco profile image
Thiago Pacheco

Definitely, it is a good practice to write tests.
I didn't include here because the article would get too long, but I could definitely create a part 2 of this article talking about tests, if that would be interesting.