Comments (5)
我这样写可以达成预期,但看起来很不优雅,官方有推荐的方式吗?
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.
I didn't see any difference between the two methods, and besides, gin itself is not officially supported
from kratos.
I didn't see any difference between the two methods, and besides, gin itself is not officially supported
There are some differences here:
- I put the registration of the
customMiddleware
middleware at the end - 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. - finally,I can print logs with trace context
from kratos.
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.
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)
- [Question] 如何使用json.Marshal 作为http server 返回的序列化工具 HOT 2
- [Question] The middleware is Executed at the end of the request? HOT 7
- [Question] How to limit HTTP request size? HOT 6
- The trace_id between requests is getting mixed up HOT 4
- [Question] How should I create a kratos project HOT 1
- net: lookupIPAddr dns resolving panic by data race. HOT 4
- [Question] The pprof profile is not valid HOT 4
- [Feature] Replace `PGV` by `protovalidate` HOT 7
- [Question] Pubsub Implementation HOT 3
- [Question]How to print trace.id in log log HOT 8
- Request context canceled during graceful shutdown HOT 3
- [Question]How to do unit testing? HOT 5
- [Question] How to make kratos grpc transfer data larger than 4MB in size ? HOT 4
- The service startup error could not be printed correctly HOT 1
- [Question] The rules before and after loading the configuration file are inconsistent. Can they be improved? HOT 8
- How to print out all request routes, including intercepted or intercepted requests without content type HOT 3
- [Feature] Whether to consider supporting Filebeat access HOT 3
- errors had been ignore or covered when too much err happend HOT 1
- proto. When the field of the query string passed by the front end is an empty string, the field parsed by the back end is nil. HOT 3
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 kratos.