Created
November 20, 2018 21:48
-
-
Save lu-moreira/0a30adf3281835dd0a00ef416be4c057 to your computer and use it in GitHub Desktop.
Getting params gin.wrapH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/json" | |
"log" | |
"net/http" | |
"github.com/gin-gonic/gin" | |
httptransport "github.com/go-kit/kit/transport/http" | |
) | |
type key string | |
const paramsKey key = "params" | |
func meuWrap(h http.Handler) gin.HandlerFunc { | |
return func(c *gin.Context) { | |
myParams := make(map[string]string) | |
for _, lala := range c.Params { | |
myParams[lala.Key] = lala.Value | |
} | |
ctx := context.WithValue(c, paramsKey, myParams) | |
r := c.Request.WithContext(ctx) | |
h.ServeHTTP(c.Writer, r) | |
} | |
} | |
func main() { | |
router := gin.Default() | |
requestURIHandler := httptransport.NewServer( | |
RequestUriEndpoint(), | |
decodeRequestUri, | |
encodeResponse, | |
) | |
router.GET("/user/:id", meuWrap(requestURIHandler)) | |
router.Run(":8010") | |
} | |
func decodeRequestUri(ctx context.Context, r *http.Request) (interface{}, error) { | |
data, ok := ctx.Value(paramsKey).(map[string]string) | |
if !ok { | |
return nil, nil | |
} | |
id := data["id"] | |
return &SampleRequest{Name: id}, nil | |
} | |
func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error { | |
return json.NewEncoder(w).Encode(response) | |
} | |
func RequestUriEndpoint() endpoint.Endpoint { | |
return func(ctx context.Context, request interface{}) (interface{}, error) { | |
req := request.(SampleRequest) | |
return SampleRequest{Name: req.Name}, nil | |
} | |
} | |
type SampleRequest struct { | |
Name string `json:"name"` | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment