首页 > 其他分享 >Go - Web Application 6

Go - Web Application 6

时间:2024-09-05 15:14:39浏览次数:6  
标签:Web alexedwards Application session go Go data side scs

Stateful HTTP

A nice touch to improve our user experience would be to display a one-time confirmation message which the user sees after they’ve added a new snippet. Like so:

A confirmation message like this should only show up for the user once (immediately after creating the snippet) and no other users should ever see the message. If you’ve been programming for a while already, you might know this type of functionality as a flash message or a toast.

To make this work, we need to start sharing data (or state) between HTTP requests for the same user. The most common way to do that is to implement a session for the user.

 

Choosing a session manager

There are a lot of security considerations when it comes to working with sessions, and proper implementation is not trivial. Unless you really need to roll your own implementation, it’s a good idea to use an existing, well-tested, third-party package here.

I recommend using either gorilla/sessions , or alexedwards/scs , depending on your project’s needs.

  • gorilla/sessions is the most established and well-known session management package for Go. It has a simple and easy-to-use API, and let’s you store session data client-side (in signed and encrypted cookies) or server-side (in a database like MySQL, PostgreSQL or Redis). However — importantly — it doesn’t provide a mechanism to renew session IDs (which is necessary to reduce risks associated with session fixation attacks if you’re using one of the server-side session stores).
  • alexedwards/scs lets you store session data server-side only. It supports automatic loading and saving of session data via middleware, has a nice interface for type-safe manipulation of data, and does allow renewal of session IDs. Like gorilla/sessions , it also supports a variety of databases (including MySQL, PostgreSQL and Redis).

In summary, if you want to store session data client-side in a cookie then gorilla/sessions is a good choice, but otherwise alexedwards/scs is generally the better option due to the ability to renew session IDs.

For this project we’ve already got a MySQL database set up, so we’ll opt to use alexedwards/scs and store the session data server-side in MySQL.

zzh@ZZHPC:/zdata/Github/snippetbox$ go get github.com/alexedwards/scs/v2
go: downloading github.com/alexedwards/scs/v2 v2.8.0
go: added github.com/alexedwards/scs/v2 v2.8.0
zzh@ZZHPC:/zdata/Github/snippetbox$ go get github.com/alexedwards/scs/mysqlstore
go: downloading github.com/alexedwards/scs/mysqlstore v0.0.0-20240316134038-7e11d57e8885
go: added github.com/alexedwards/scs/mysqlstore v0.0.0-20240316134038-7e11d57e8885

 

标签:Web,alexedwards,Application,session,go,Go,data,side,scs
From: https://www.cnblogs.com/zhangzhihui/p/18398496

相关文章