I follow it from this URL https://github.com/gorilla/sessions
import (
"net/http"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte("something-very-secret"))
func CreateSessionEndPoint(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", allowedURL)
session, _ := store.Get(req, "login")
session.Values["userDetails"] = "Object values here...."
session.Save(req, w)
}
And for the retreival of seesion, this is my code.
func CheckSessionEndPoint(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", allowedURL)
session, err := store.Get(req, "login")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
val := session.Values["userDetails"]
//var details = &UserDetails{}
details, _ := val.(*UserDetails)
fmt.Println(details) //This will display null when calling from angular.
json.NewEncoder(w).Encode(details)
}
Also, the angular is installed outside my go project.
I manage to access the go URL by putting this “w.Header().Set(“Access-Control-Allow-Origin”, allowedURL)” on every function endpoint
Below is my anuglar code on calling the go API:
import { Injectable } from '@angular/core';
import { Http, Request, RequestOptions, RequestMethod } from '@angular/http';
import { map, takeUntil, tap } from 'rxjs/operators';
import { UserLoginComponent } from '../../components/user-login/user-login.component';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
constructor(private http:Http) { }
login(userDetails:IUserDetails){
let _body = JSON.stringify(userDetails);
return this.http.post("http://localhost:8080/api/CreateSession",_body).pipe(map(res=>res.json()));
}
getSession(){
var session = this.http.get("http://localhost:8080/api/checkSession").pipe(map(res=>res.json()));
console.log(session.subscribe((posts)=>{
console.log("get session",posts);
}));
}
}
export interface IUserDetails{
ID:number,
FirstName:string,
LastName:string,
Email:string,
Password:string,
BirthDate:Date,
CreatedDate:Date
}