Git Product home page Git Product logo

Comments (5)

ChangSZ avatar ChangSZ commented on July 22, 2024

我这样写可以达成预期,但看起来很不优雅,官方有推荐的方式吗?

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/gin-gonic/gin"
	kgin "github.com/go-kratos/gin"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/http"
	"go.opentelemetry.io/otel"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

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())
		}

		if c, ok := kgin.FromGinContext(ctx); ok {
			c.Request = c.Request.WithContext(ctx)
		}
		reply, err = handler(ctx, req)
		return
	}
}

func main() {
	router := gin.Default()

	tp := sdktrace.NewTracerProvider()
	otel.SetTracerProvider(tp)

	logger := log.With(log.NewStdLogger(os.Stdout),
		"ts", log.DefaultTimestamp,
		"caller", log.DefaultCaller,
		"trace.id", tracing.TraceID(),
		"span.id", tracing.SpanID(),
	)
	log.SetLogger(logger)

	// 使用kratos中间件
	router.Use(kgin.Middlewares(recovery.Recovery(), tracing.Server(), logging.Server(logger), customMiddleware))

	router.GET("/helloworld/:name", func(ctx *gin.Context) {
		name := ctx.Param("name")
		log.Context(ctx.Request.Context()).Info("hello world")
		if name == "error" {
			// 返回kratos 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.Logger(logger),
		kratos.Server(
			httpSrv,
		),
	)
	if err := app.Run(); err != nil {
		panic(err)
	}
}

from kratos.

shenqidebaozi avatar shenqidebaozi commented on July 22, 2024

I didn't see any difference between the two methods, and besides, gin itself is not officially supported

from kratos.

ChangSZ avatar ChangSZ commented on July 22, 2024

I didn't see any difference between the two methods, and besides, gin itself is not officially supported

There are some differences here:

image

  1. I put the registration of the customMiddleware middleware at the end
  2. In the customMiddleware middleware, I wrote the context of trace into gin.Context.Request, so that I can get the context of trace in the input parameter of the router's handler.
  3. finally,I can print logs with trace context

from kratos.

shenqidebaozi avatar shenqidebaozi commented on July 22, 2024

Non official support for gin. If an exception occurs, it may be due to incomplete implementation. We recommend using official standard support. Or you can fix it directly

from kratos.

ChangSZ avatar ChangSZ commented on July 22, 2024

Non official support for gin. If an exception occurs, it may be due to incomplete implementation. We recommend using official standard support. Or you can fix it directly

ok~ thx

from kratos.

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.