|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/go-kratos/kratos/v2" |
| 8 | + "github.com/go-kratos/kratos/v2/errors" |
| 9 | + "github.com/go-kratos/kratos/v2/log" |
| 10 | + "github.com/go-kratos/kratos/v2/transport" |
| 11 | + "github.com/go-kratos/kratos/v2/transport/http" |
| 12 | + "github.com/go-redis/redis/v8" |
| 13 | + |
| 14 | + "github.com/go-kratos/examples/helloworld/helloworld" |
| 15 | + "github.com/go-kratos/examples/http/session/sessions" |
| 16 | +) |
| 17 | + |
| 18 | +// go build -ldflags "-X main.Version=x.y.z" |
| 19 | +var ( |
| 20 | + // Name is the name of the compiled software. |
| 21 | + Name = "session" |
| 22 | + // Version is the version of the compiled software. |
| 23 | + // Version = "v1.0.0" |
| 24 | +) |
| 25 | + |
| 26 | +// server is used to implement helloworld.GreeterServer. |
| 27 | +type server struct { |
| 28 | + helloworld.UnimplementedGreeterServer |
| 29 | + |
| 30 | + store *sessions.RedisStore |
| 31 | +} |
| 32 | + |
| 33 | +// SayHello implements helloworld.GreeterServer |
| 34 | +func (s *server) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) { |
| 35 | + if tr, ok := transport.FromServerContext(ctx); ok { |
| 36 | + if ht, ok := tr.(*http.Transport); ok { |
| 37 | + // get a session |
| 38 | + session, err := s.store.Get(ht, "session") |
| 39 | + if err != nil { |
| 40 | + return nil, errors.InternalServer("INTERNAL_ERROR", "get session error") |
| 41 | + } |
| 42 | + |
| 43 | + // modified the value of the key, and save |
| 44 | + session.Values["key"] = "value" |
| 45 | + if err = session.Save(ht); err != nil { |
| 46 | + return nil, errors.InternalServer("INTERNAL_ERROR", "save session error") |
| 47 | + } |
| 48 | + |
| 49 | + // delete session |
| 50 | + //session.Options.MaxAge = -1 |
| 51 | + //if err = session.Save(ht); err != nil { |
| 52 | + // return nil, errors.InternalServer("INTERNAL_ERROR", "save session error") |
| 53 | + //} |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return &helloworld.HelloReply{Message: fmt.Sprintf("Hello %+v", in.Name)}, nil |
| 58 | +} |
| 59 | + |
| 60 | +func main() { |
| 61 | + rdCmd := redis.NewClient(&redis.Options{ |
| 62 | + Addr: "127.0.0.1:6379", |
| 63 | + }) |
| 64 | + store, err := sessions.NewRedisStore(rdCmd, []byte("secret")) |
| 65 | + store.SetMaxAge(10 * 24 * 3600) |
| 66 | + if err != nil { |
| 67 | + log.Fatal(err) |
| 68 | + } |
| 69 | + |
| 70 | + httpSrv := http.NewServer( |
| 71 | + http.Address(":8000"), |
| 72 | + ) |
| 73 | + |
| 74 | + s := &server{store: store} |
| 75 | + helloworld.RegisterGreeterHTTPServer(httpSrv, s) |
| 76 | + |
| 77 | + app := kratos.New( |
| 78 | + kratos.Name(Name), |
| 79 | + kratos.Server( |
| 80 | + httpSrv, |
| 81 | + ), |
| 82 | + ) |
| 83 | + |
| 84 | + if err := app.Run(); err != nil { |
| 85 | + log.Fatal(err) |
| 86 | + } |
| 87 | +} |
0 commit comments