我正在try 将会话添加到用GO编写的现有http服务器.我的代码如下所示

type HttpServer struct {
    getRoutes  map[string]http.HandlerFunc // pattern => handler
    postRoutes map[string]http.HandlerFunc
    server     http.Server
}
func (s *HttpServer) Run() {
    address := "127.0.0.1:8080"
    s.server = http.Server{
        Addr:           address,
        Handler:        s,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    log.Fatal(s.server.ListenAndServe())
}
func (s *HttpServer) ServeHTTP(writer http.ResponseWriter, r *http.Request) {
     ...
}

我想使用以下工具添加会话 https://pkg.go.dev/github.com/alexedwards/scs/v2#SessionManager.LoadAndSave

链接中的示例代码为

    mux := http.NewServeMux()
    mux.HandleFunc("/put", putHandler)
    mux.HandleFunc("/get", getHandler)

    // Wrap your handlers with the LoadAndSave() middleware.
    http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))

示例代码将mux传递给LoadAndSave,然后将新的处理程序传递给HTTP.ListenAndServe(port,newHandler).在我的例子中,处理程序来self 添加到*HttpServer struct 中的ServeHttp方法.示例中的处理程序来自多路复用器.

我是新来的.是否可以将ServeHTTP方法传递给LoadAndSave并使用从LoadAndSave返回的处理程序?如果不是,有没有办法将我的示例中使用的HTTP.Server struct 字段传递给HTTP.ListenAndServe(Port,Handler)?

推荐答案

As noted in Peter's answer, the LoadAndSave() method from alexedwards/scs/v2 expects an http.Handler interface as an argument.
Since your HttpServer type has a ServeHTTP method with the correct signature, it satisfies the http.Handler interface, and you can pass an instance of your HttpServer type to the LoadAndSave method.

但是您的Run()方法应该有一个sessionManager *scs.SessionManager作为参数:

func (s *HttpServer) Run(sessionManager *scs.SessionManager) {
    address := "127.0.0.1:8080"
    
    // Wrap your HttpServer with the LoadAndSave middleware.
    handlerWithSessions := sessionManager.LoadAndSave(s)
    
    ...
}

That means creating and configuring the SessionManager outside this method (with scs.New()), and passing it in when you call Run.
There, you can set sessionManager as a field in the HttpServer struct.
That will allow your (s *HttpServer) ServeHTTP(writer http.ResponseWriter, r *http.Request) to retrieve it.

例如:

package main

import (
    "github.com/alexedwards/scs/v2"
    "log"
    "net/http"
    "time"
)

type HttpServer struct {
    getRoutes     map[string]http.HandlerFunc // pattern => handler
    postRoutes    map[string]http.HandlerFunc
    server        http.Server
    sessionManager *scs.SessionManager
}

func (s *HttpServer) Run(sessionManager *scs.SessionManager) {
    address := "127.0.0.1:8080"
    
    // Set the sessionManager field
    s.sessionManager = sessionManager
    
    // Wrap your HttpServer with the LoadAndSave middleware.
    handlerWithSessions := sessionManager.LoadAndSave(s)
    
    s.server = http.Server{
        Addr:           address,
        Handler:        handlerWithSessions, // Use the wrapped handler
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    
    log.Fatal(s.server.ListenAndServe())
}

func (s *HttpServer) ServeHTTP(writer http.ResponseWriter, r *http.Request) {
    // Access the session via the sessionManager field
    session := s.sessionManager.Load(r)
    
    // Use the session, e.g. session.Put, session.Get, etc.
    // ...
}

func main() {
    // Create and configure the session manager
    sessionManager := scs.New()
    sessionManager.Lifetime = 24 * time.Hour
    
    // Create your custom HttpServer
    httpServer := &HttpServer{
        getRoutes:  make(map[string]http.HandlerFunc),
        postRoutes: make(map[string]http.HandlerFunc),
    }
    
    // Start the server with the session manager
    httpServer.Run(sessionManager)
}

Go相关问答推荐

如何模拟嵌入. FS?

带有条件的for循环中缺少RETURN语句

mockgen不创建模拟

理解Golang中的IOTA和常量

如何使用 html/template 在 golang 中运行一个范围内的范围

如何绕过深层 xml,没有嵌套循环?

Go 中的sync.Cond 与 Wait 方法

Kperf 构建失败

如何从Go项目连接Microsoft Access数据库?

命令行参数在 Golang 程序中不正确地接受为参数

为什么我只收到部分错误而不是我启动的 goroutines 的所有错误?

在 Go 中公开公共 JWK

获取不带类型参数的泛型 struct 的类型名称

Gorm 在保存/创建时序列化 struct

切片到数组指针的转换

Go 使用 struct 作为接口而不实现所有方法

Golang API 的 HTTPS

如何从 docker-compose 命令运行 2 个不同的命令:

如何使用 httputil.ReverseProxy 设置 X-Forwarded-For

Go 错误:cannot use generic type without instantiation