I am using browsers localStorage
to store a value, but while using google chrome, when we refresh the page using window.location.reload()
, lo
// main.go
package main
import (
"encoding/json"
"fmt"
"log"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
)
// Article - Our struct for all articles
type Article struct {
Id string `json:"Id"`
Title string `json:"Title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
var Articles []Article
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the HomePage!")
fmt.Println("Endpoint Hit: homePage")
}
func returnAllArticles(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint Hit: returnAllArticles")
json.NewEncoder(w).Encode(Articles)
}
func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
for _, article := range Articles {
if article.Id == key {
json.NewEncoder(w).Encode(article)
}
}
}
func createNewArticle(w http.ResponseWriter, r *http.Request) {
// get the body of our POST request
// unmarshal this into a new Article struct
// append this to our Articles array.
reqBody, _ := ioutil.ReadAll(r)
var article Article
json.Unmarshal(reqBody, &article)
// update our global Articles array to include
// our new Article
Articles = append(Articles, article)
json.NewEncoder(w).Encode(article)
}
func deleteArticle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
for index, article := range Articles {
if article.Id == id {
Articles = append(Articles[:index], Articles[index+1:]...)
}
}
}
func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", homePage)
myRouter.HandleFunc("/articles", returnAllArticles)
myRouter.HandleFunc("/article", createNewArticle).Methods("POST")
myRouter.HandleFunc("/article/{id}", deleteArticle).Methods("DELETE")
myRouter.HandleFunc("/article/{id}", returnSingleArticle)
log.Fatal(http.ListenAndServe(":10000", myRouter))
}
func main() {
Articles = []Article{
Article{Id: "1", Title: "Hello", Desc: "Article Description", Content: "Article Content"},
Article{Id: "2", Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
}
handleRequests()
}
You need to use the correct API for Storage:
window.localStorage.setItem('value1', 'true');
What you're doing is setting a property on a variable which won't persist between page loads. Firefox is likely being too smart and recognizing that you want to actually save the value in the browser's local storage store.
LocalStorage supports only string values, not boolean or others.
Method to store and retrieve values:
Put the value into storage
localStorage.setItem('value1', 'true');
Retrieve the value from storage
var val1 = localStorage.getItem('value1');
Read more on MDN..
Try it
window.localStorage.setItem("value1", true);
var yourvar = window.localStorage.getItem("value1");