//go:build server || (!server && !client) package main import ( "log" "os" "os/signal" "syscall" "time" "github.com/noahlann/nnet/pkg/nnet" ) // This example demonstrates file-based session storage. // Sessions are persisted to disk and survive server restarts. func main() { cfg := &nnet.Config{ Addr: "tcp://:8083", Session: &nnet.SessionConfig{ Storage: "file", // 使用文件存储 Path: "./sessions_example", // Session文件存储路径 Expiration: 1 * time.Hour, // Session过期时间 }, Codec: &nnet.CodecConfig{ DefaultCodec: "json", EnableProtocolEncode: false, }, } srv, err := nnet.NewServer(cfg) if err != nil { log.Fatal("create server:", err) } // 路由1:设置Session值 srv.Router().RegisterString("set", func(ctx nnet.Context) error { // 注意:Session功能可能需要在服务器层面集成 // 这里演示如何使用Session的概念 // 实际使用中,Session应该通过Connection或Context访问 connID := ctx.Connection().ID() return ctx.Response().Write(map[string]any{ "action": "set", "conn_id": connID, "message": "session storage configured (file)", "path": cfg.Session.Path, "note": "Session API integration pending", }) }) // 路由2:获取Session信息 srv.Router().RegisterString("get", func(ctx nnet.Context) error { connID := ctx.Connection().ID() return ctx.Response().Write(map[string]any{ "action": "get", "conn_id": connID, "storage": "file", "path": cfg.Session.Path, "expiration": cfg.Session.Expiration.String(), }) }) // 路由3:计数器(演示Session持久化) srv.Router().RegisterString("counter", func(ctx nnet.Context) error { connID := ctx.Connection().ID() // 在实际实现中,这里应该从Session读取和更新计数器 return ctx.Response().Write(map[string]any{ "conn_id": connID, "message": "counter endpoint (session-based counting would be implemented here)", "note": "Session storage: file", }) }) log.Println("session_file_server listening on :8083") log.Printf("Session storage: file (%s)", cfg.Session.Path) log.Printf("Session expiration: %v", cfg.Session.Expiration) if err := srv.Start(); err != nil { log.Fatal("start server:", err) } defer srv.Stop() quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit log.Println("Shutting down... Sessions are persisted to disk.") }