gin

package
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 9, 2024 License: MIT Imports: 7 Imported by: 0

README

Go-Kratos Gin Plugin

fork by https://github.com/go-kratos/gin

Usage

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/gin-gonic/gin"
	kgin "github.com/imkouga/kratos-pkg/contrib/gin"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/http"
)

func customMiddleware(handler middleware.Handler) middleware.Handler {
	return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
		if tr, ok := transport.FromServerContext(ctx); ok {
			fmt.Println("operation:", tr.Operation())
		}
		reply, err = handler(ctx, req)
		return
	}
}

func main() {
	router := gin.Default()
	router.Use(kgin.Middlewares(recovery.Recovery(), customMiddleware))
	router.GET("/helloworld/:name", func(ctx *gin.Context) {
		name := ctx.Param("name")
		if name == "error" {
			kgin.Error(ctx, errors.Unauthorized("auth_error", "no authentication"))
		} else {
			ctx.JSON(200, map[string]string{"welcome": name})
		}
	})

	httpSrv := http.NewServer(http.Address(":8000"))
	httpSrv.HandlePrefix("/", router)

	app := kratos.New(
		kratos.Name("gin"),
		kratos.Server(
			httpSrv,
		),
	)
	if err := app.Run(); err != nil {
		log.Fatal(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContentType

func ContentType(subtype string) string

ContentType returns the content-type with base prefix.

func Error

func Error(c *gin.Context, err error)

Error encodes the object to the HTTP response.

func FromGinContext

func FromGinContext(ctx context.Context) (c *gin.Context, ok bool)

FromGinContext returns the gin.Context value stored in ctx, if any.

func Middlewares

func Middlewares(m ...middleware.Middleware) gin.HandlerFunc

Middlewares return middlewares wrapper

func NewGinContext

func NewGinContext(ctx context.Context, c *gin.Context) context.Context

NewGinContext returns a new Context that carries gin.Context value.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL