Gin: GET and POST together, the same handler.

Created on 8 Nov 2018  ·  3Comments  ·  Source: gin-gonic/gin

I'm trying to use gqlgen (https://github.com/99designs/gqlgen) with gin.

I'm using the code below but I have doubts.

package server

import (
    "myProject/graphql"
    "github.com/99designs/gqlgen/handler"
    "github.com/gin-gonic/gin"
)

func Start() {
    r := gin.Default()

    r.GET("/query", gin.WrapH(handler.Playground("GraphQL playground", "/api")))
    r.GET("/api", gin.WrapH(handler.GraphQL(graphql.NewExecutableSchema(graphql.Config{Resolvers: &graphql.Resolver{}}))))
    r.POST("/api", gin.WrapH(handler.GraphQL(graphql.NewExecutableSchema(graphql.Config{Resolvers: &graphql.Resolver{}}))))

    r.Run()
}

As you can see I need to repeat the lines:

r.GET("/api", gin.WrapH(handler.GraphQL(graphql.NewExecutableSchema(graphql.Config{Resolvers: &graphql.Resolver{}}))))
r.POST("/api", gin.WrapH(handler.GraphQL(graphql.NewExecutableSchema(graphql.Config{Resolvers: &graphql.Resolver{}}))))

Is this correct?

Can I just have GET and POST both with the same handler function?

(I opened https://github.com/99designs/gqlgen/issues/418 for this problem).

Most helpful comment

Why don't you just

graphHandler := gin.WrapH(handler.GraphQL(graphql.NewExecutableSchema(graphql.Config{Resolvers: &graphql.Resolver{}})))
r.GET("/api", graphHandler)
r.POST("/api", graphHandler)

yes, this still repeats the line, but makes modifiying it easier.

I have to agree with @olegsobchuk , in a normal WebAPI GET and POST would do different things, and therefor have different handlers - but people do what they do

All 3 comments

Gin uses httprouter router and according to source code from THIS STRING it is impossible.

BTW
I can't even imagine what are you going to do with GET and POST on the same action

Why don't you just

graphHandler := gin.WrapH(handler.GraphQL(graphql.NewExecutableSchema(graphql.Config{Resolvers: &graphql.Resolver{}})))
r.GET("/api", graphHandler)
r.POST("/api", graphHandler)

yes, this still repeats the line, but makes modifiying it easier.

I have to agree with @olegsobchuk , in a normal WebAPI GET and POST would do different things, and therefor have different handlers - but people do what they do

    router.GET("/a/b", h)
    router.POST("/a/b", h)

it's ok!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kekemuyu picture kekemuyu  ·  3Comments

cxk280 picture cxk280  ·  3Comments

ccaza picture ccaza  ·  3Comments

ghost picture ghost  ·  3Comments

gplume picture gplume  ·  3Comments