GTW (Gateway) is a new web development framework for Go, designed to make web application codebases more maintainable and elegant. It introduces an annotation-driven approach that decouples logic from configuration, allowing developers to create more contextual and easily maintainable code.
Many popular Go web frameworks, such as Fiber and Gin, use a handler-based approach to create web APIs. While powerful, this approach can lead to several issues in large-scale projects:
- Lack of clear structure in route definitions and handler logic
- Limited contextual information and difficulty in sharing dependencies
- Challenges in implementing clean dependency injection
- Reduced code reusability due to anonymous functions
- Increased difficulty in unit testing isolated handlers
Example of typical route definition in Fiber:
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
GTW addresses these issues by introducing an annotation-driven, struct-based approach that separates configuration from handler logic. This solution offers:
- Clear structure for defining APIs and their associated handlers
- Improved contextuality and organization of related routes
- Built-in support for dependency injection
- Enhanced code reusability through struct methods
- Better testability due to decoupled components
Example of API definition in GTW:
type Foo struct {
Metadata `prefix:"api"`
Bar Service[int] `name:"test"`
Get Handler `route:"/foo" method:"GET"`
}
func (f *Foo) GetHandler(httpCtx *HttpCtx) (Status, Response) {
output := map[string]any{
"Hello": t.Bar.Value(),
}
return 200, JSON(output)
}
Feature | GTW | Fiber/Gin |
---|---|---|
API Definition | Struct-based with annotations | Handler based |
Route Configuration | Decoupled from logic | Mixed with handler logic |
Dependency Injection | Built-in support | Requires manual implementation |
Code Organization | Hierarchical and contextual | Flat and potentially scattered |
To start using GTW, follow these steps:
-
Install GTW (assuming it's available as a package):
go get github.com/vedadiyan/gtw
-
Define your API structure:
type Foo struct { Get gtw.Handler `route:"/get" method:"GET"` }
-
Implement your handlers:
func (f *Foo) GetHandler(httpCtx *gtw.HttpCtx) (gtw.Status, gtw.Response) { // Your logic here }
-
Register your API with the default server:
func init() { gtw.DefaultServer().Register(new(TestAPI)) }
-
Run your server (implementation details may vary):
func main() { err := gtw.DefaultServer().ListenAndServe(&http.Server{Addr: ":8080"}) if err != nil { log.Fatal(err) } }
- Annotation-driven API definition
- Struct-based organization for improved maintainability
- Built-in support for dependency injection
- Clear separation of route configuration and handler logic
- Flexible response handling