GO Http Framework (Golang)
- Easier Error Handling
- Middleware
- Sub-Router (route grouping)
- Customizable Response
- Lightweight
- Based on net/http
Please make sure Go version >= 1.22
go get github.com/gohf-http/gohf/v6
import (
"github.com/gohf-http/gohf/v6"
"github.com/gohf-http/gohf/v6/response"
)
router.GET("/greeting", func(c *gohf.Context) gohf.Response {
name := c.Req.GetQuery("name")
if name == "" {
return response.Error(
http.StatusBadRequest,
errors.New("Name is required"),
)
}
greeting := fmt.Sprintf("Hello, %s!", name)
return response.Text(http.StatusOK, greeting)
})
Return gohf.Response
to handle the error. (response.Error
in this example)
router.Use(func(c *gohf.Context) gohf.Response {
token := c.Req.GetHeader("Authorization")
if !isValidToken(token) {
return response.Error(
http.StatusUnauthorized,
errors.New("Invalid token"),
)
}
return c.Next()
})
Router.Use
create a middleware.
This is how middleware works in GoHF.
authRouter := router.SubRouter("/auth")
authRouter.Use(AuthMiddleware)
userRouter := authRouter.SubRouter("/users")
// GET /auth/users
userRouter.GET("/", ...)
// POST /auth/users
userRouter.POST("/", ...)
// GET /auth/users/{id}
userRouter.GET("/{id}", ...)
Router.SubRouter
create a sub-router.
Middlewares will be recursively applied to all endpoints of the router, including those of its nested sub-routers.
You can define a customizable response by implementing gohf.Response
interface.
type Response interface {
Send(http.ResponseWriter, *gohf.Request)
}
Refer to response package for examples.
This is one of my favorite features, as it promotes a centralized response handler and simplifies adding additional functionality, such as logging.
package main
import (
"errors"
"log"
"net/http"
"github.com/gohf-http/gohf/v6"
"github.com/gohf-http/gohf/v6/response"
)
func main() {
router := gohf.New()
router.GET("/greeting", func(c *gohf.Context) gohf.Response {
name := c.Req.GetQuery("name")
if name == "" {
return response.Error(
http.StatusBadRequest,
errors.New("Name is required"),
)
}
return response.JSON(http.StatusOK, map[string]string{
"Hello": name,
})
})
router.Use(func(c *gohf.Context) gohf.Response {
return response.Error(
http.StatusNotFound,
errors.New("Page not found"),
)
})
mux := router.CreateServeMux()
log.Fatal(http.ListenAndServe(":8080", mux))
}
Give a ⭐️ if this project helped you!