Comments (7)
@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.
haha ok!
Just use
var w http.ResponseWriter = c.Writer
var req *http.Request = c.Req
from gin.
Yes, I got it, replace:
func HomeHandler(w http.ResponseWriter, r *http.Request) {
....
}
with
func HomeHandler(c *gin.Context) {
}
nice web framework!
from gin.
@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.
@manucorporat nice work, looks good. i will use it in my next project.
from gin.
@saggit great! check out the implementation, so simple:
https://github.com/gin-gonic/gin/blob/develop/utils.go#L16-L26
from gin.
@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)
- Attach Response Headers (or middlewares) to redirected requests (CORS issues) HOT 1
- Should context.GetRawData() also copy body to BodyBytesKey? HOT 3
- YAML BindBody should not parse JSON content HOT 1
- Gin do not support javascript ? HOT 5
- Does gin.Recovery() run before or after Group middleware? HOT 1
- How can i prevent a http connection to close HOT 3
- BasicAuth is not suitable for proxy auth
- Can't get status as expected from context.Status() HOT 1
- Gin Context implementation breaks context.Context contract HOT 4
- [Suggestions] Introducing an AI-powered robot to assist with daily issue and pull request (PR) tasks.
- Need c.JSON() response like behaviour for c.SSEvent() response for supporting first party clients like OpenAI SDK HOT 2
- custom time.Time type can not use bindQuery get a value. HOT 3
- configure server parameters HOT 1
- The binding:"required" tag does not seem to work for struct types HOT 3
- Is there a way to preserve order in JSON on response? HOT 1
- redirect is not success HOT 1
- I want to use shouldmindbodywith first and then use formafile, but it doesn't work right now HOT 3
- Extend the routing tree entry
- Transparent decompression for gzip, deflate, etc? HOT 1
- Custom time.Time type can not use bindQuery get a value 2 HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from gin.