我已经导入了包
import (
"github.com/gorilla/sessions"
"github.com/gorilla/mux"
//CORS
"github.com/rs/cors"
"github.com/justinas/alice"
)
并定义 store 和 main 方法如下
var store = sessions.NewCookieStore([]byte("something-very-secret"))
const My_UI="http://localhost:3000"
func init() {
store.Options = &sessions.Options{
Path: "/",
MaxAge: 3600 * 1, // 1 hour
HttpOnly: true,
}
}
var router = mux.NewRouter() //MUX Handeler
//MAIN Function
func main() {
c := cors.New(cors.Options{
AllowedOrigins: []string{My_UI},
})
router.HandleFunc("/submitted",Login)
router.HandleFunc("/check",GetSession)
http.Handle("/", router)
chain := alice.New(c.Handler).Then(router) //CORS enable
fmt.Println("server started at port 8080")
http.ListenAndServe(":8080", chain)
}
在我的方法中,我按照 gorilla doc 中的描述创建并设置了会话值
func Login(w http.ResponseWriter, r *http.Request) {
fmt.Println("In login----------->")
sess := GetCon() //get connection session
defer sess.Close() //close session
c := sess.DB("mydb").C("users") //collection-> select db table
session1, _ := store.Get(r, "loginSession") //login session
//parse json data
form := LoginUser{}
err := json.NewDecoder(r.Body).Decode(&form)
if err !=nil {
fmt.Println(err)
}
皈依舞
相关分类