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)
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:
net/http
standard library-- - Any net/http compatible http or middleware pkgcan be used in the Go ecosystem Designed for modular/composable APIs - middleware, inline middleware, Route group and sub-router installation
- No external dependencies ---Purely just Go 1.7 stdlib net / http
- Powerful --- There are many Companies are using, such as: Pressly, CloudFlare, Heroku, 99Designs
- Lightweight --- cloc'd in ~1000 LOC for the chi router
- It's fast
- What I like most is that the old http handlers and middleware you wrote for other net/http compatible routers will still work fine. Let’s get started
The code above is the focus of some best practices
Use a single package To implement routing logic, group them, and then mount them:
- Verify the API so that you can update the api without breaking old clients:
- Use middleware as an extension. Code that uses a lot of routes is very cumbersome. In fact, it can be turned into link middleware, such as: authorization, setting response headers, compression, request logs, rate limiting, etc.
- chi routing has a method called walk. Parameters received by this method:
- A callback.
- Every The defined routes will all be called back and receive 4 parameters:
- The string of the actual route
- Processor (function), handles requests for a given route
- A list of middleware defined in a given route (middleware is a relatively simple function, which will be called before the handler is called, so they will be used before request processing, authorization, etc.)
- In my case, I will simply poll Routes and prints all defined routes. This gives me an overview of all available routes. Next we build a todo package, which actually saves our todo logic.
Notes
routes.go,
so that it will be easy to find- .
-
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
- Are you intimidated by how easy it is? You can view this project on GitHub https://github.com/tonyalaribe/todoapi/tre....
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TointegrateGolangserviceswithexistingPythoninfrastructure,useRESTAPIsorgRPCforinter-servicecommunication,allowingGoandPythonappstointeractseamlesslythroughstandardizedprotocols.1.UseRESTAPIs(viaframeworkslikeGininGoandFlaskinPython)orgRPC(withProtoco

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

To write a Dockerfile for basic Golang applications, you need to understand three core steps: selecting a suitable image, building an application, and packaging the operating environment. 1. Use multi-stage construction to reduce volume. In the first stage, use golang:1.21 image to compile and generate executable files. In the second stage, only copy the compilation results and run them. 2. Set CGO_ENABLED=0 to avoid C library dependencies, unify the working directory such as /app and use the COPY instruction to copy the code. It is recommended to cooperate with .dockerignore to exclude irrelevant files; 3. Specify specific Go versions such as golang:1.21 instead of latest to ensure the controllable version and improve CI/CD consistency and compatibility.

Yes, multiple Go versions can be installed on the same machine. It can be easily implemented using version management tools such as gvm or goenv. Gvm supports package collections, which are suitable for cross-environment testing, while goenv is similar to rbenv and is easy to operate. After installation, version switching is performed through commands such as gvmininstallgo1.20 and gvmusego1.20, and the default version is set. If you do not use the tools, you can manually install different versions to separate directories and switch by modifying the PATH environment variables, such as configuring the shell alias go120 and go121 to quickly switch. Regardless of the method, you should confirm the current version through government and check the Go binary path in the IDE to

TogetenvironmentvariablesinGo,useos.Getenv(),butconsiderLookupEnvforexistencechecks.1.Useos.Getenv("VAR_NAME")toretrieveavariable’svalueasastring,returningemptyifunset.2.Useos.LookupEnv()todistinguishbetweenunsetandemptyvariables.3.Provided

GousessignificantlylessmemorythanPythonwhenrunningwebservicesduetolanguagedesignandconcurrencymodeldifferences.1.Go'sgoroutinesarelightweightwithminimalstackoverhead,allowingefficienthandlingofthousandsofconnections.2.Itsgarbagecollectorisoptimizedfo

sync.WaitGroup is used to wait for a group of goroutines to complete the task. Its core is to work together through three methods: Add, Done, and Wait. 1.Add(n) Set the number of goroutines to wait; 2.Done() is called at the end of each goroutine, and the count is reduced by one; 3.Wait() blocks the main coroutine until all tasks are completed. When using it, please note: Add should be called outside the goroutine, avoid duplicate Wait, and be sure to ensure that Don is called. It is recommended to use it with defer. It is common in concurrent crawling of web pages, batch data processing and other scenarios, and can effectively control the concurrency process.

The key to installing Go is to select the correct version, configure environment variables, and verify the installation. 1. Go to the official website to download the installation package of the corresponding system. Windows uses .msi files, macOS uses .pkg files, Linux uses .tar.gz files and unzip them to /usr/local directory; 2. Configure environment variables, edit ~/.bashrc or ~/.zshrc in Linux/macOS to add PATH and GOPATH, and Windows set PATH to Go in the system properties; 3. Use the government command to verify the installation, and run the test program hello.go to confirm that the compilation and execution are normal. PATH settings and loops throughout the process
