Home >Backend Development >Golang >How to Write APIs Like a Pro in Go with GopherLight
GopherLIght
Hey folks, first I would like to thank you for choosing to use our project. Even though he is small, we did it with great enthusiasm! To start using it you first have to have go installed, let's assume you already have it. Then install the main modules of the framework, which are req and router
go get github.com/BrunoCiccarino/GopherLight/router go get github.com/BrunoCiccarino/GopherLight/req
Already downloaded? Phew! Now we can make our first hello world.
package main import ( "fmt" "github.com/BrunoCiccarino/GopherLight/router" "github.com/BrunoCiccarino/GopherLight/req" ) func main() { app := router.NewApp() // Define a route that responds to a GET request at "/hello". app.Get("/hello", func(r *req.Request, w *req.Response) { w.Send("Hello, World!") }) fmt.Println("Server listening on port 3333") app.Listen(":3333") }
Pretty simple, right? And there’s way more we can do with GopherLight. Keep reading for a full breakdown of HTTP methods and our Request and Response tools.
Supported HTTP Methods
Here’s the list of HTTP methods you can use with router.App. Each of these allows you to set up routes to handle different types of requests. Let’s dive in!
Retrieves data without modifying anything.
Example: Fetching a list of items or reading user details.
Sends data to create a new resource.
Example: Submitting a form or adding a new item to a list.
Usage: app.Put(path, handler)
Updates or replaces a resource. It’s an “overwrite” action.
Example: Updating a full user profile.
Usage: app.Delete(path, handler)
Deletes a resource.
Example: Removing a user or deleting a post.
Usage: app.Patch(path, handler)
Partially updates a resource without replacing everything.
Example: Updating just the email on a user profile.
Usage: app.Options(path, handler)
Returns allowed HTTP methods for a URL, mainly for CORS preflight requests.
Usage: app.Head(path, handler)
Like GET, but no response body. Use it to check if a resource exists.
Usage: app.Connect(path, handler), app.Trace(path, handler)
Advanced methods: CONNECT sets up a tunnel (for SSL), and TRACE is for debugging, echoing back the request.
Now that you’ve seen the routes, let’s talk about the Request and Response objects, your go-to helpers for handling incoming requests and sending responses.
Each request handler gets a Request object loaded with info on the incoming request. Here’s what you can do with it:
go get github.com/BrunoCiccarino/GopherLight/router go get github.com/BrunoCiccarino/GopherLight/req
The Response object helps you send a reply back to the client. Here's what you can do:
package main import ( "fmt" "github.com/BrunoCiccarino/GopherLight/router" "github.com/BrunoCiccarino/GopherLight/req" ) func main() { app := router.NewApp() // Define a route that responds to a GET request at "/hello". app.Get("/hello", func(r *req.Request, w *req.Response) { w.Send("Hello, World!") }) fmt.Println("Server listening on port 3333") app.Listen(":3333") }
We’ve got a batch of middlewares ready for you to add some serious functionality to your Go web app. Each of these middlewares brings its own magic—security, logging, timeouts, and more! Let’s break them down one by one. ?
Our AuthMiddleware helps protect your routes with JSON Web Tokens (JWT). It’s flexible, letting you customize the secret key, error handling, and token extraction method.
Setup
To get started, configure your JWT settings using JWTConfig:
app.Get("/greet", func(r *req.Request, w *req.Response) { name := r.QueryParam("name") if name == "" { name = "stranger" } w.Send("Hello, " + name + "!") })
Need to allow cross-origin requests? No problem! Our CORSMiddleware configures the Cross-Origin Resource Sharing (CORS) settings to make your API accessible from other domains.
Config Options
app.Get("/user", func(r *req.Request, w *req.Response) { user := map[string]string{"name": "Gopher", "language": "Go"} w.JSON(user) })
Our CSRFMiddleware protects against Cross-Site Request Forgery by validating a CSRF token sent with each request. Use GenerateCSRFToken() to create a secure token, then validate it with your own isValidToken function.
import ( "github.com/BrunoCiccarino/GopherLight/middleware" ) config := middleware.JWTConfig{ SecretKey: []byte("your_secret_key"), } app.Use(middleware.NewAuthMiddleware(config))
And don’t forget to generate tokens with:
go get github.com/BrunoCiccarino/GopherLight/router go get github.com/BrunoCiccarino/GopherLight/req
Want to keep track of what’s happening on your server? LoggingMiddleware logs each request, including the method, path, and time taken. It’s a great way to stay informed on app performance and any unusual activity.
package main import ( "fmt" "github.com/BrunoCiccarino/GopherLight/router" "github.com/BrunoCiccarino/GopherLight/req" ) func main() { app := router.NewApp() // Define a route that responds to a GET request at "/hello". app.Get("/hello", func(r *req.Request, w *req.Response) { w.Send("Hello, World!") }) fmt.Println("Server listening on port 3333") app.Listen(":3333") }
Each request will be logged like this:
Avoid those endless waits by setting time limits on request processing with TimeoutMiddleware. This middleware will cancel the request if it doesn’t complete in time, sending a 504 Gateway Timeout status to the client.
app.Get("/greet", func(r *req.Request, w *req.Response) { name := r.QueryParam("name") if name == "" { name = "stranger" } w.Send("Hello, " + name + "!") })
The Plugin interface is super simple but super powerful. It gives you a single method: Register. This lets you hook into the app’s routing system to add any routes you need—whether it’s a new API endpoint, a webhook, or anything else you can imagine.
The Register Method
Here’s the magic part of the Plugin interface:
app.Get("/user", func(r *req.Request, w *req.Response) { user := map[string]string{"name": "Gopher", "language": "Go"} w.JSON(user) })
The Register method accepts a route function that lets you define new routes in your plugin by specifying:
Let’s say you want to create a plugin that adds a simple endpoint at /hello-plugin to greet users. Here’s what the plugin would look like:
import ( "github.com/BrunoCiccarino/GopherLight/middleware" ) config := middleware.JWTConfig{ SecretKey: []byte("your_secret_key"), } app.Use(middleware.NewAuthMiddleware(config))
To load a plugin, simply create an instance and call Register in your main app setup:
corsOptions := middleware.CORSOptions{ AllowOrigin: "*", AllowMethods: []string{"GET", "POST"}, } app.Use(middleware.CORSMiddleware(corsOptions))
Each plugin can add as many routes as needed. Just call route multiple times in your Register function to define additional endpoints. Use different HTTP methods, paths, and handlers to shape your plugin’s functionality however you want.
The above is the detailed content of How to Write APIs Like a Pro in Go with GopherLight. For more information, please follow other related articles on the PHP Chinese website!