2

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)?

1 Answer 1

1

Yes. *HttpServer implements the http.Handler interface so you can pass it to LoadAndSave:

func (s *HttpServer) Run() {
    address := "127.0.0.1:8080"
    s.server = http.Server{
        Addr:           address,
        Handler:        sessionManager.LoadAndSave(s),
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    log.Fatal(s.server.ListenAndServe())
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.