Giter VIP home page Giter VIP logo

Comments (7)

manucorporat avatar manucorporat commented on April 26, 2024 75

@saggit I know you probably are not interested but... I just added a new helper function gin.Wrap(http.HandleFunc)

func main() {
    router := gin.Default()
    router.GET("/", gin.Wrap(handler))
    router.Run(":8080")
}

func handler(w http.ResponseWriter, req *http.Request) {
    fmt.Fprint(w, "something")
}

from gin.

manucorporat avatar manucorporat commented on April 26, 2024 25

haha ok!
Just use

var w http.ResponseWriter = c.Writer
var req *http.Request = c.Req

from gin.

saggit avatar saggit commented on April 26, 2024 23

Yes, I got it, replace:

func HomeHandler(w http.ResponseWriter, r *http.Request) {
        ....
}

with

func HomeHandler(c *gin.Context) {

    }

nice web framework!

from gin.

zatamine avatar zatamine commented on April 26, 2024 3

@manucorporat, I was trying to separate out the HTTP request handling libraries for my project. I was able to do that with Gorilla Mux and Chi router using their standard request and response handlers. But in case of Gin and Fiber, these library uses context instead of the standard handlers. And I am unable to manage my codes at routes and controllers as it has been a compulsory thing to pass the context (i.e. c *gin.Context) in my Router interface and the Controllers. Is there any way to manage the code for GIN or FIBER so that I can use standard handlers within my router interface and Controllers so that I can easily switch between the HTTP request routers (i.e. GIN/MUX/FIBER/CHI etc.).

The Router interface

package router

import (
	"github.com/gin-gonic/gin"
)

type Router interface {
	GET(uri string, f func(c *gin.Context))
	POST(uri string, f func(c *gin.Context))
	DELETE(uri string, f func(c *gin.Context))
	SERVE(port string)
	GROUP(uri string) *gin.RouterGroup
}

GIN router implementation

package router

import (
	"github.com/gin-gonic/gin"
)

type ginRouter struct{}

var (
	ginDispatcher = gin.Default()
)

func NewGinRouter() Router {
	return &ginRouter{}
}

func (*ginRouter) GET(uri string, f func(c *gin.Context)) {
	ginDispatcher.GET(uri, f)
}

func (*ginRouter) POST(uri string, f func(c *gin.Context)) {
	ginDispatcher.POST(uri, f)
}

func (*ginRouter) DELETE(uri string, f func(c *gin.Context)) {
	ginDispatcher.DELETE(uri, f)
}

func (*ginRouter) SERVE(port string) {
	_ = ginDispatcher.Run(port)
}

func (*ginRouter) GROUP(uri string) *gin.RouterGroup {
	return ginDispatcher.Group(uri)
}

One of my controller tightly coupled with GIN router due to use of context (c *gin.Context)


import (
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm2.0/model"
)

type AccountController interface {
	GetAccounts(c *gin.Context)
	AddAccount(c *gin.Context)
	DeleteAccount(c *gin.Context)
}

type accountController struct {
	accountService model.AccountService
}

//Constructor Function
func NewAccountController(service model.AccountService) AccountController {
	return &accountController{
		accountService: service,
	}
}

//GET
func (a *accountController) GetAccounts(c *gin.Context) {
	accounts, err := a.accountService.FindAll()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Error while fetching the accounts"})
		return
	}

	c.JSON(http.StatusOK, accounts)
}

//POST
func (a *accountController) AddAccount(c *gin.Context) {
	var account model.Account
	if err := c.ShouldBindJSON(&account); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	a.accountService.Create(&account)

	c.JSON(http.StatusOK, account)
}

//DELETE
func (a *accountController) DeleteAccount(c *gin.Context) {
	var account model.Account
	if err := c.ShouldBindJSON(&account); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	} 

	ErrOnDelete := a.accountService.Delete(&account)
	if ErrOnDelete!= nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Could not delete the account"})
		return
	}

	c.JSON(http.StatusOK, account)
}

Mux Router implementation incompatible with the Router interface coz I have been using GIN router.

package router

import (
	"net/http"
	"fmt"


	"github.com/gorilla/mux"
)

type muxRouter struct {}

var (
	muxDispatcher = mux.NewRouter()
)

func NewMuxRouter() Router {
	return &muxRouter{}
}

func (*muxRouter) GET(uri string, f func(w http.ResponseWriter, r *http.Request)){
	muxDispatcher.HandleFunc(uri, f).Methods("GET")
}

func (*muxRouter) POST(uri string, f func(w http.ResponseWriter, r *http.Request)){
	muxDispatcher.HandleFunc(uri, f).Methods("POST")
}

func (*muxRouter) SERVE(port string){
	fmt.Printf("Mux HTTP server running on port %v", port)
	http.ListenAndServe(port, muxDispatcher)
}

Try this

package router

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

type ginRouter struct{}

var (
	ginDispatcher = gin.Default()
)

func NewGinRouter() Router {
	return &ginRouter{}
}

func (*ginRouter) GET(path string, f func(w http.ResponseWriter, req *http.Request)) {
	ginDispatcher.GET(path, gin.WrapF(f))

}
func (*ginRouter) POST(path string, f func(w http.ResponseWriter, req *http.Request)) {
	ginDispatcher.POST(path, gin.WrapF(f))
}

func (*ginRouter) SERVE(addr string) {
	fmt.Println("Running Gin HTTP server")
	ginDispatcher.Run(addr)
}

from gin.

saggit avatar saggit commented on April 26, 2024

@manucorporat nice work, looks good. i will use it in my next project.

from gin.

manucorporat avatar manucorporat commented on April 26, 2024

@saggit great! check out the implementation, so simple:
https://github.com/gin-gonic/gin/blob/develop/utils.go#L16-L26

from gin.

SujalKokh avatar SujalKokh commented on April 26, 2024

@manucorporat, I was trying to separate out the HTTP request handling libraries for my project. I was able to do that with Gorilla Mux and Chi router using their standard request and response handlers. But in case of Gin and Fiber, these library uses context instead of the standard handlers. And I am unable to manage my codes at routes and controllers as it has been a compulsory thing to pass the context (i.e. c *gin.Context) in my Router interface and the Controllers. Is there any way to manage the code for GIN or FIBER so that I can use standard handlers within my router interface and Controllers so that I can easily switch between the HTTP request routers (i.e. GIN/MUX/FIBER/CHI etc.).

The Router interface

package router

import (
	"github.com/gin-gonic/gin"
)

type Router interface {
	GET(uri string, f func(c *gin.Context))
	POST(uri string, f func(c *gin.Context))
	DELETE(uri string, f func(c *gin.Context))
	SERVE(port string)
	GROUP(uri string) *gin.RouterGroup
}

GIN router implementation

package router

import (
	"github.com/gin-gonic/gin"
)

type ginRouter struct{}

var (
	ginDispatcher = gin.Default()
)

func NewGinRouter() Router {
	return &ginRouter{}
}

func (*ginRouter) GET(uri string, f func(c *gin.Context)) {
	ginDispatcher.GET(uri, f)
}

func (*ginRouter) POST(uri string, f func(c *gin.Context)) {
	ginDispatcher.POST(uri, f)
}

func (*ginRouter) DELETE(uri string, f func(c *gin.Context)) {
	ginDispatcher.DELETE(uri, f)
}

func (*ginRouter) SERVE(port string) {
	_ = ginDispatcher.Run(port)
}

func (*ginRouter) GROUP(uri string) *gin.RouterGroup {
	return ginDispatcher.Group(uri)
}

One of my controller tightly coupled with GIN router due to use of context (c *gin.Context)


import (
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm2.0/model"
)

type AccountController interface {
	GetAccounts(c *gin.Context)
	AddAccount(c *gin.Context)
	DeleteAccount(c *gin.Context)
}

type accountController struct {
	accountService model.AccountService
}

//Constructor Function
func NewAccountController(service model.AccountService) AccountController {
	return &accountController{
		accountService: service,
	}
}

//GET
func (a *accountController) GetAccounts(c *gin.Context) {
	accounts, err := a.accountService.FindAll()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Error while fetching the accounts"})
		return
	}

	c.JSON(http.StatusOK, accounts)
}

//POST
func (a *accountController) AddAccount(c *gin.Context) {
	var account model.Account
	if err := c.ShouldBindJSON(&account); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	a.accountService.Create(&account)

	c.JSON(http.StatusOK, account)
}

//DELETE
func (a *accountController) DeleteAccount(c *gin.Context) {
	var account model.Account
	if err := c.ShouldBindJSON(&account); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	} 

	ErrOnDelete := a.accountService.Delete(&account)
	if ErrOnDelete!= nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Could not delete the account"})
		return
	}

	c.JSON(http.StatusOK, account)
}

Mux Router implementation incompatible with the Router interface coz I have been using GIN router.

package router

import (
	"net/http"
	"fmt"


	"github.com/gorilla/mux"
)

type muxRouter struct {}

var (
	muxDispatcher = mux.NewRouter()
)

func NewMuxRouter() Router {
	return &muxRouter{}
}

func (*muxRouter) GET(uri string, f func(w http.ResponseWriter, r *http.Request)){
	muxDispatcher.HandleFunc(uri, f).Methods("GET")
}

func (*muxRouter) POST(uri string, f func(w http.ResponseWriter, r *http.Request)){
	muxDispatcher.HandleFunc(uri, f).Methods("POST")
}

func (*muxRouter) SERVE(port string){
	fmt.Printf("Mux HTTP server running on port %v", port)
	http.ListenAndServe(port, muxDispatcher)
}

from gin.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.