Skip to content

gohf-http/gohf

Repository files navigation

GoHF ✨

Test Go Reference Release Documentation Maintenance License

GO Http Framework (Golang)

❓ WHY GoHF

📍 Getting started

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"
)

Hello GoHF Example

🪄 Features

Feature: Easier Error Handing

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)

Feature: Middleware

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.

middleware

Feature: Sub-Router

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.

Feature: Customizable Response

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.

Hello GoHF Example

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))
}

🌟 Show your support

Give a ⭐️ if this project helped you!