I am trying to add sessions to an existing http server written in go. I have code like the following
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) {
...
}
I would like to add sessions using https://pkg.go.dev/github.com/alexedwards/scs/v2#SessionManager.LoadAndSave
The example code in the link is
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
// Wrap your handlers with the LoadAndSave() middleware.
http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
The example code passes mux into LoadAndSave, then passes the new handler into http.ListenAndServe(port, newHandler). In my case the handler comes from a ServeHttp method I added to the *HttpServer struct. The handler in the example case comes from the mux.
I am new to go. Is it possible to pass my ServeHTTP method into LoadAndSave and use the handler returned from LoadAndSave? If not, is there a way to pass the http.Server struct fields used in my example into http.ListenAndServe(Port, handler)?