Home >Backend Development >Golang >Elegant implementation of Golang REST API architecture
In this series, we will go through how to build a product-level REST API TODO list, a sustainable extension architecture, starting with routing and code interfaces, then adding a mongo database and a badger data layer, and then Is the authorization protocol layer (OAuth 2.0)
In this series we will use chi routing.Why choose to use Chi instead of the standard library or Gin or router-x for routing?
Well, actually it doesn’t matter what you choose to use. No matter what you use for routing, the concepts discussed in this series will be useful. But there are the following advantages that make me think Chi-router is superior to most alternatives:
is 100% compatible with thenet/http
standard library-- - Any net/http compatible http or middleware pkg can be used in the Go ecosystem Designed for modular/composable APIs - middleware, inline middleware, Route group and sub-router installation
The code above is the focus of some best practices
Use a single package To implement routing logic, group them, and then mount them:
r.Mount("/api/todo", todo.Routes())The handler has the function signature of func (w http.ResponseWriter,r *http.Request)
, which means that this handler is no different from the net/http writing method you use the standard library.Use render.JSON, an encoding/json wrapper, which will automatically escape all html in your JSON response and set the content-type to application/json
In our next article in this series, we will continue to support configuration and shared state. Most projects usually require additional configuration, such as database connections, etc. We will discuss this in the next article.
Recommended tutorial: "Go Tutorial"
The above is the detailed content of Elegant implementation of Golang REST API architecture. For more information, please follow other related articles on the PHP Chinese website!