<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ivano Dalmasso on Medium]]></title>
        <description><![CDATA[Stories by Ivano Dalmasso on Medium]]></description>
        <link>https://medium.com/@ivano-dalmasso?source=rss-90a990ce37dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*c-Um1zGLK8LfXhy9</url>
            <title>Stories by Ivano Dalmasso on Medium</title>
            <link>https://medium.com/@ivano-dalmasso?source=rss-90a990ce37dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:53:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivano-dalmasso/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Social application with Vue.js and GO]]></title>
            <link>https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4d0caa37ddac?source=rss-90a990ce37dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d0caa37ddac</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[indexeddb]]></category>
            <dc:creator><![CDATA[Ivano Dalmasso]]></dc:creator>
            <pubDate>Wed, 14 Apr 2021 10:56:18 GMT</pubDate>
            <atom:updated>2021-04-15T01:28:02.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*9RcvJALOdCOUBieIJCCMEg.jpeg" /><figcaption>Logo credits to vuejs.org and golang.org</figcaption></figure><h4>Create and serve a twitter like application with vue.js and golang PART 9: Store authentication token with indexedDB</h4><p>This is the ninth part of this serie. Check here all the parts:</p><ul><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4e4db0cdde64">Part1: Setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64b3adee8dac">Part2: Getting started with VUE</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-24a1d1e7137d">Part3: Components &amp; slots</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-3a11d506fc38">Part4: Vuex first setup</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-ef364b572422">Part5: Vuex finalization</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-a22a1afb76eb">Part6: Forms and data in Vuex</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-d9e563466b66">Part7: Connection with golang server</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-64978f7c381f">Part8: Token based authentication</a></li><li>Part9: Store token with indexedDB (this)</li></ul><p>In this lesson we’ll change the authentication setup on the client layer so that the access login and logout won’t be lost closing the browser. This will be a little short one, you can find the code, that will upgrade only the frontend, <a href="https://github.com/idalmasso/go-vue-tutorial-frontend/releases/tag/v0.9">here</a>.</p><h4>Saving authentication data to the client</h4><p>After last lesson the application asked us an authentication process with username and password, and then gave us a token that we could use to call the various APIs that we needed.</p><p>Now we have a problem here: our client did not store this token anywhere if not in the store, and this is being cleared each time the browser is refreshed.</p><p>To solve this we are going to store the authentication data in indexedDB, a special store that all modern browser can use to save some data (i.e. return values from API).</p><p>Now, please avoid thinking about using local storage for saving this info, this is not secure at all, read <a href="https://dev.to/rdegges/please-stop-using-local-storage-1i04">this</a> for understanding better why.</p><p>Actually there are a couple of tools that could be used to make this duty a little easier:</p><ul><li>vuex-persist is a package that let’s you tell your store to use a personalized persistence layer, once setup everything will stay there</li><li>idb is a package that will make working with indexedDB easier and gives functions that returns promises, feature that indexedDB does not have natively</li></ul><p>Actually I won’t use these two packages in this tutorial, we will instead go with pure indexedDB code.</p><h4>Create a utility file to access indexedDB</h4><p>As first create a file with some utilities functions to use for our use case. In this we are going to give the functionalities to create the database and use it for storing and retrieving the data of the currently logged in user.</p><p>Create a file /store/indexedDBUtils.js with the following code:</p><pre>const DB_NAME = &quot;authDB&quot;;<br>const DB_VERSION = 1;<br>let DB;</pre><pre>export default {<br>  async getDb() {<br>    return new Promise((resolve, reject) =&gt; {<br>      if (DB) {<br>        return resolve(DB);<br>      }<br>      let request = window.indexedDB.open(DB_NAME, DB_VERSION);</pre><pre>request.onerror = e =&gt; {<br>        console.log(&quot;Error opening db&quot;, e);<br>        reject(&quot;Error&quot;);<br>      };</pre><pre>request.onsuccess = e =&gt; {<br>        DB = e.target.result;<br>        resolve(DB);<br>      };</pre><pre>request.onupgradeneeded = e =&gt; {<br>        console.log(&quot;onupgradeneeded&quot;);<br>        let db = e.target.result;<br>        let objectStore = db.createObjectStore(&quot;userAuth&quot;, {<br>          autoIncrement: true,<br>          keyPath: &quot;username&quot;<br>        });<br>      };<br>    });<br>  },<br>  async addUser(user) {<br>    //I ONLY want to have 1 user in this db... I delete all other before<br>    let db = await this.getDb();</pre><pre>return new Promise(resolve =&gt; {<br>      let trans = db.transaction([&quot;userAuth&quot;], &quot;readwrite&quot;);<br>      trans.oncomplete = () =&gt; {<br>        resolve();<br>      };</pre><pre>let store = trans.objectStore(&quot;userAuth&quot;);<br>      store.openCursor().onsuccess = e =&gt; {<br>        let cursor = e.target.result;<br>        if (cursor) {<br>          if (cursor.value.username != user.username) {<br>            store.delete(cursor.value.username);<br>          }<br>          cursor.continue();<br>        }<br>      };<br>      store.put(user);<br>    });<br>  },<br>  async removeUser(user) {<br>    if (!user || !user.username) {<br>      return;<br>    }<br>    let db = await this.getDb();</pre><pre>return new Promise(resolve =&gt; {<br>      let trans = db.transaction([&quot;userAuth&quot;], &quot;readwrite&quot;);<br>      trans.oncomplete = () =&gt; {<br>        resolve();<br>      };</pre><pre>let store = trans.objectStore(&quot;userAuth&quot;);<br>      store.delete(user.username);<br>    });<br>  },<br>  async getUser() {<br>    let db = await this.getDb();</pre><pre>return new Promise(resolve =&gt; {<br>      let trans = db.transaction([&quot;userAuth&quot;], &quot;readwrite&quot;);<br>      trans.oncomplete = () =&gt; {<br>        resolve(user);<br>      };<br>      let user = null;<br>      let store = trans.objectStore(&quot;userAuth&quot;);<br>      store.openCursor().onsuccess = e =&gt; {<br>        let cursor = e.target.resul<br>        if (!cursor) return;<br>        console.log(cursor.value);<br>        user = cursor.value;<br>      };<br>    });<br>  }<br>};</pre><p>The first lines are self explanatory, we define the name of the store in indexedDB where we will save our data. Then we exports the functions that will give the access to our 4 functionalities in a promise-like way: get the database instance, create a user, remove a user, and retrieve a user.</p><p>The getDb function returns a promise that open the database and then, if needed (with the event “onupgradeneeded”) it updates it adding the userAuth store, that is actually what you can call a “table” in a relational database. Note that the userAuth also gets as “keyPath” the name of the key of the objects to use. In this case, we will insert the user data using the username as key. This call sets the DB variable we have created before, so that it can be used as first call in each of the others functions.</p><p>AddUser is the first function where we can see actually how indexedDB works. It gets the database instance as first, then it creates a “transaction” on the database. The result of this transaction is what will decide the return status of the promise. As first thing, here, we get a objectStore instance of the store created before (“userAuth”), then we delete all the records that are inside it (this is because we only want to save the actual user in this database, remember that we are actually in the user browser). At the end we store the actual user data using the store.put() call.</p><p>RemoveUser is actually the same as addUser, it just removes the user from the database, while getUser actually creates a cursor and returns the first record found in the database (remember, there should be only one!).</p><p>Actually this is all we need to make this work, now we can work again in the store to update it and use this functionality.</p><h4>Use the utility functions in the store</h4><p>In the index.js file of the auth store update the login action, so that if the login is successful we can add the user to the indexedDB, and if there is an error the user is removed:</p><pre>async login(context, { username, password }) {<br>....<br>.then(data =&gt; {<br>  dbUtils.addUser({ username: username, token: data.token });<br>  context.commit(&quot;LOGIN&quot;, <br>    {<br>      username: username, token: data.token<br>    }<br>  );<br>})<br>.catch(error =&gt; {<br>  dbUtils.removeUser({ username: username });<br>  context.commit(&quot;LOGOUT&quot;);<br>  throw error;<br>});</pre><p>The same update can be done in the signup action, while the logout action should only get the removeUser part.<br>Now after a user login or signup, the “user” object is automatically put in the store.</p><p>Create now a new action to retrieve the user when needed:</p><pre>async loadUser(context) {<br>  dbUtils.getUser().then(user =&gt; {<br>    console.log(user);<br>    if (user &amp;&amp; user != {})<br>      context.commit(&quot;LOGIN&quot;, user);<br>  });<br>}</pre><p>This actually just check if there is a user in the database. If the answer is positive, the store actually commit the login mutation with this user. Remember that the token is actually inside of the user object, so everything now is going to persist.</p><p>We now have to dispatch this action when needed.<br>The easiest and more immediate place where to do this is in the mounted method of the app itself, so just go in the ./App.vue file and add a mounted() function to the configuration object of our app like this:</p><pre>mounted() {<br>    this.$store.dispatch(&quot;auth/loadUser&quot;);<br>}</pre><p>And this is all we have to do about this.</p><p>Now you can try to launch the application, and it will check in the database if there is a user. If it is then found, it will be stored in the store and its token sent to our server, like before.</p><p>In the next lesson we are going to add mongoDB to store the data on server side, so the application will be finally able to be called as “complete”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d0caa37ddac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social application with Vue.js and GO]]></title>
            <link>https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64978f7c381f?source=rss-90a990ce37dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/64978f7c381f</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Ivano Dalmasso]]></dc:creator>
            <pubDate>Mon, 29 Mar 2021 14:21:12 GMT</pubDate>
            <atom:updated>2021-04-14T10:56:53.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*9RcvJALOdCOUBieIJCCMEg.jpeg" /><figcaption>Logo credits to vuejs.org and golang.org</figcaption></figure><h4>Create and serve a twitter like application with vue.js and golang PART 8: Token based authentication</h4><p>This is the eighth part of this serie. Check here all the parts:</p><ul><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4e4db0cdde64">Part1: Setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64b3adee8dac">Part2: Getting started with VUE</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-24a1d1e7137d">Part3: Components &amp; slots</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-3a11d506fc38">Part4: Vuex first setup</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-ef364b572422">Part5: Vuex finalization</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-a22a1afb76eb">Part6: Forms and data in Vuex</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-d9e563466b66">Part7: Connection with golang server</a></li><li>Part8: Token based authentication (This)</li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4d0caa37ddac">Part9: Store authentication token with indexedDB</a></li></ul><p>In this lesson we’ll add an authentication layer in both the client vue application and in the go server. As a plus, we will also add the endpoint to get a single user, that will be used for the “user” page in the vue page.</p><p>We will update both the frontend and the backend in this session, you can find the code here:</p><ul><li><a href="https://github.com/idalmasso/go-vue-tutorial-backend/releases/tag/v0.8">backend</a></li><li><a href="https://github.com/idalmasso/go-vue-tutorial-frontend/releases/tag/v0.8">frontend</a></li></ul><h4>Manage a simple token-based authentication</h4><p>Let’s start adding a file where we’ll manage the routes regarding authentication. Add a file “<em>/endpoints/auth.go”</em>. There we will insert all the logic for registration, login and logout operation for a user.</p><p>Generation and check of the passwords hash are going to be done using the standard library <em>bcrypt </em>(“<em>golang.org/x/crypto/bcrypt</em>”) while for the jwt token creation and check we are going to use <em>dgrijalva/jwt-go </em>(“<em>github.com/dgrijalva/jwt-go</em>”), so just import them.</p><p>Note that the creation of the token needs a server side secret to be used, so we just can create a function to take it from an environment variable, like this (in “<em>endpoints/utils.go</em>”):</p><pre>func getSecret() string{<br> secret:=os.Getenv(&quot;ACCESS_SECRET&quot;)<br> if secret==&quot;&quot;{<br>  //That&#39;s surely a big secret this way...<br>  secret=&quot;sdmalncnjsdsmf&quot;<br> }<br> return secret<br>}</pre><p>Obviously if the secret is empty, a real server should panic and throw an error in our real world, but this is ok for our case for now.</p><p>Now, in auth.go create a struct that will be used to pass the username/password data to the endpoints for creation of the user and for login:</p><pre>type User struct{<br>  Username string `json:&quot;username&quot;`<br>  Password string `json:&quot;password&quot;`<br>}</pre><p>Then create the two endpoints too (note that we also create an array of users as “in memory” database, for now) and also a method to create a new token:</p><pre>var users map[string][]byte = make(map[string][]byte)<br>var idxUsers int =0<br><br>//getTokenUserPassword returns a jwt token for a user if the //password is ok<br>func getTokenUserPassword(w http.ResponseWriter, r *http.Request) {<br>  var u User<br>  err:=json.NewDecoder(r.Body).Decode(&amp;u)<br>  if err!=nil{<br>    http.Error(w, &quot;cannot decode username/password struct&quot;,http.StatusBadRequest)<br>    return<br>  }<br>  //here I have a user!<br>  //Now check if exists <br>  passwordHash, found:= users[u.Username]<br>  if !found{<br>    http.Error(w, &quot;Cannot find the username&quot;, http.StatusNotFound)<br>  }	<br>  err=bcrypt.CompareHashAndPassword(passwordHash, []byte(u.Password))<br>  if err!=nil{<br>    return<br>  }<br>  token, err:=createToken(u.Username)<br>  if err!=nil{<br>    http.Error(w, &quot;Cannot create token&quot;, http.StatusInternalServerError)<br>    return<br>  }<br>  sendJSONResponse(w, struct {Token string `json:&quot;token&quot;`}{ token })	<br>}<br><br>func createUser(w http.ResponseWriter, r *http.Request){<br>  var u User<br>  err := json.NewDecoder(r.Body).Decode(&amp;u)<br>  if err!=nil{<br>    http.Error(w, &quot;Cannot decode request&quot;, http.StatusBadRequest)<br>    return<br>  }<br>  if _, found:= users[u.Username]; found{<br>    http.Error(w,&quot;User already exists&quot;, http.StatusBadRequest)<br>    return<br>  }<br>  //If I&#39;m here-&gt; add user and return a token<br>  value, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)<br>  users[u.Username]=value<br>  token, err:=createToken(u.Username)<br>  if err!=nil{<br>    http.Error(w, &quot;Cannot create token&quot;, http.StatusInternalServerError)<br>    return<br>  }	<br>  sendJSONResponse(w, struct {Token string `json:&quot;token&quot;`}{ token })<br>}</pre><pre>func createToken(username string) (string, error) {<br>  var err error<br>  //Creating Access Token  <br>  atClaims := jwt.MapClaims{}<br>  atClaims[&quot;authorized&quot;] = true<br>  atClaims[&quot;username&quot;] = username<br>  atClaims[&quot;exp&quot;] = time.Now().Add(time.Minute * 15).Unix()<br>	at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)<br>	secret:= getSecret()<br>  token, err := at.SignedString([]byte(secret))<br>  if err != nil {<br>     return &quot;&quot;, err<br>  }<br>  return token, nil<br>}</pre><p>The “createToken” function gets a string username and create a token with some claims, for example that the token should be used by exactly that user, and the expiration is 15 minutes. Then the function returns a token created using the application secret that could be used for the authentication for 15 minutes (but we have still to implement this).</p><p>The other 2 functions are actually pretty similar: both decode the body of the request as a json object of the type we created before, then the <em>createUser </em>try to add it to the “database”, while the <em>getTokenUserPassword </em>actually checks if the user exists. Then, if all these checks return successfully, these functions returns a “JSONified” object with a newly created token.</p><p>These two functions are actually the handlers for the functions of login and registration for the site, so just add the two following lines in the <em>AddRouterEndpoints </em>function of the utils.go file for binding them to the actual routes:</p><pre>r.HandleFunc(&quot;/api/auth/login&quot;,<br>             getTokenUserPassword).Methods(&quot;POST&quot;) r.HandleFunc(&quot;/api/auth/create-user&quot;, createUser).Methods(&quot;POST&quot;)</pre><p>We now have a way to actually registrate and login a user. This is actually useless until we block the access of some parts of the server side.</p><p>Let’s address this, adding these two methods to the <em>utils.go</em> file:</p><pre>func checkTokenHandler(next http.HandlerFunc) http.HandlerFunc{<br>  return func(w http.ResponseWriter, r *http.Request) {<br>    header := r.Header.Get(&quot;Authorization&quot;)<br>    bearerToken := strings.Split(header, &quot; &quot;)<br>    if len(bearerToken)!=2{<br>      http.Error(w, &quot;Cannot read token&quot;, http.StatusBadRequest)<br>      return<br>    }<br>    if bearerToken[0] != &quot;Bearer&quot;{<br>      http.Error(w, &quot;Error in authorization token. it needs to be in form of &#39;Bearer &lt;token&gt;&#39;&quot;, http.StatusBadRequest)<br>      return<br>    }		<br>    token, ok :=checkToken(bearerToken[1]); <br>    if !ok{<br>      http.Error(w, &quot;Unauthorized&quot;, http.StatusUnauthorized)<br>      return<br>    }<br>    claims, ok := token.Claims.(jwt.MapClaims)<br>    if ok &amp;&amp; token.Valid {	<br>      username, ok := claims[&quot;username&quot;].(string)<br>      if !ok {<br>        http.Error(w, &quot;Unauthorized&quot;, http.StatusUnauthorized)<br>        return <br>      }<br>      //check if username actually exists<br>      if _, ok := users[username]; !ok{<br>        http.Error(w, &quot;Unauthorized, user not exists&quot;, http.StatusUnauthorized)<br>        return <br>      } <br>      //Set the username in the request, so I will use it in check after!<br>      context.Set(r, &quot;username&quot;, username)<br>    }<br>    next(w, r)<br>  }<br>}<br><br>func checkToken (tokenString string) (*jwt.Token, bool) {<br>  token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {<br>    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {<br>      return nil, fmt.Errorf(&quot;unexpected signing method: %v&quot;, token.Header[&quot;alg&quot;])<br>    }<br>    return []byte(getSecret()), nil<br>  })<br>  if err!=nil{<br>    return nil, false<br>  }<br>  if _, ok := token.Claims.(jwt.Claims); !ok &amp;&amp; !token.Valid {<br>    return nil, false<br>  }<br>  return token, true<br>}</pre><p>The <em>checkToken </em>function get as input a string token, and returns a jwt.Token object after having validated its default values.</p><p>The <em>checkTokenHandler </em>instead returns an actual http handler function that can be used “before” the real handler of a route. In this handler it gets the token from the “<em>Authorization</em>” header, it makes an easy check of the formation of this header (it have to be “Bearer &lt;token&gt;”). Then, it get the jwt.Token object from the <em>checkToken</em> function, and makes an additional control on the existence of the username in the token in the database. It then sets the username in the context of the request, so we could also use it in the real request, and calls the real http handler that we want to call that is being passed to the <em>checkTokenHandler </em>function.</p><p>Note that if any of the checks fail, the real route is not called, and an error is returned to the client. We now just have to decorate all the routes we want to “protect” with an authentication process with this method, to have some protection, in <em>addRouterEndpoints</em>:</p><pre>func AddRouterEndpoints(r *mux.Router) *mux.Router {<br>...<br>  r.HandleFunc(&quot;/api/posts&quot;,checkTokenHandler(addPost))<br>    .Methods(&quot;POST&quot;)<br>  r.HandleFunc(&quot;/api/posts/{POST_ID}&quot;,checkTokenHandler(deletePost))<br>    .Methods(&quot;DELETE&quot;)<br>  r.HandleFunc(&quot;/api/posts/{POST_ID}/comments&quot;,<br>    checkTokenHandler(addComment)).Methods(&quot;POST&quot;)<br>...</pre><p>These three api are actually protected with a token authentication now.</p><p>A user will have to send a token with a valid user with this api to actually, for example, add a post. A little problem is still here, if a user “A” send a post with author user “B”, the system still accepts it, so let’s make this little fix too, in the posts.go file, add the following function:</p><pre>func isUsernameContextOk(username string, r *http.Request) bool {<br>	usernameCtx, ok:=context.Get(r, &quot;username&quot;).(string)<br>	if !ok{<br>		return false<br>	}<br>	if usernameCtx!=username{<br>		return false<br>	}<br>	return true<br>}</pre><p>This just get the username from the requests, and compares it to a username we want to check. We can call this function in the three functions “<em>addPost</em>”, “<em>deletePost</em>” and “<em>addComment</em>” just after the deserialization of the post (or the comment) to check if the user of the post is the actual one in the request, like this:</p><pre>if !isUsernameContextOk(post.Username, r){<br>  http.Error(w, &quot;Cannot manage post for another user&quot;, http.StatusUnauthorized)<br>  return <br>}</pre><p>Regarding the authentication, one last thing that can be done, is to give a way to refresh the token if it is almost expired, by using the old one to get a new one:</p><pre>func getTokenByToken(w http.ResponseWriter, r *http.Request){<br>  //Here I already have the token checked... Just get the username from Request context<br>  username, ok :=context.Get(r,&quot;username&quot;).(string)<br>  if !ok{<br>    http.Error(w, &quot;Cannot check username&quot;,  http.StatusInternalServerError)<br>    return<br>  }<br>  token, err:=createToken(username)<br>  if err!=nil{<br>    http.Error(w, &quot;Cannot create token&quot;, http.StatusInternalServerError)<br>    return<br>  }<br>  sendJSONResponse(w, struct {Token string}{ token })<br>}</pre><p>and actually bind it in <em>addRouterEndpoints</em></p><pre>r.HandleFunc(&quot;/api/auth/token&quot;,checkTokenHandler(getTokenByToken))<br>  .Methods(&quot;GET&quot;)</pre><p>This is actually not a real world scenario, obviously. This in reality should be used with a two token authentication/authorization style, so one token with long expiration used for authentication that is used to get an authorization token with short expiration. This is only a demonstrative snippet of code about how to do it.</p><p>As last thing for this tutorial chapter, we can add an api endpoint protected by token authentication to get a user data to show in the Users page.</p><p>Just add a new file ‘<em>/endpoints/users.go</em>’ and set the code of the endpoint there:</p><pre>func getUser(w http.ResponseWriter, r *http.Request) {<br>  log.Println(&quot;getuser called&quot;)<br>  vars := mux.Vars(r)<br>  user, ok := vars[&quot;USERNAME&quot;]<br>  if !ok {<br>    http.Error(w, &quot;Cannot find username in request&quot;,http.StatusBadRequest)<br>    return<br>  }<br>  if _, ok :=users[user]; ok{<br>    sendJSONResponse(w, <br>    struct{Username string `json:&quot;username&quot;`; <br>       Description string `json:&quot;description&quot;` }{user ,  &quot;&quot;})<br>    return<br>  }<br>  http.Error(w, &quot;Cannot find user&quot;, http.StatusNotFound)<br>}</pre><p>and use the decorating handlers we used before to check the authentication in the <em>addRouterEnpoints </em>function</p><pre>r.HandleFunc(&quot;/api/users/{USERNAME}&quot;,<br>  checkTokenHandler(getUser)).Methods(&quot;GET&quot;)</pre><p>Now we have to update the client vue application to use these new functionalities.</p><h4>Authentication in the client application</h4><p>Let’s start updating the client application to use the authentication on the server. Start with editing the “<em>store/authStore/index.js</em>” file, removing the actual default username and adding in the state a new token empty string. Then we will have to manipulate these two states in the LOGIN and LOGOUT mutations like this:</p><pre>LOGIN(state, { username, token }) {<br>   state.user.loggedIn = true;<br>   state.user.username = username;<br>   state.user.token = token;<br>},<br>LOGOUT(state) {<br>   state.user.loggedIn = false;<br>   state.user.username = &quot;&quot;;<br>   state.user.token = &quot;&quot;;<br>}</pre><p>Then we just have to update the actual actions and just make sure to call the correct apis (note: the logout action does actually not invalidate the token in the server side, in fact we did not manage a “token state” in the server right by now, so it just remove the token from memory and cleanup the user in the client application)</p><pre>async login(context, { username, password }) {<br>    return fetch(&quot;http://localhost:3000/api/auth/login&quot;, {<br>      method: &quot;POST&quot;,<br>      body: JSON.stringify({<br>                             username: username, <br>                             password: password })<br>      })<br>      .then(response =&gt; {<br>        if (!response.ok) {<br>          throw new Error(&quot;Cannot login!&quot;);<br>        }<br>        return response.json();<br>      }).then(data =&gt; {<br>         context.commit(&quot;LOGIN&quot;,<br>              { username: username, token: data.token });<br>      }).catch(error =&gt; {<br>          context.commit(&quot;LOGOUT&quot;);<br>          throw error;<br>        });<br>    },<br>async logout(context) {<br>    context.commit(&quot;LOGOUT&quot;);<br>},<br>async signup(context, { username, password }) {<br>    return fetch(&quot;http://localhost:3000/api/auth/create-user&quot;, {<br>      method: &quot;POST&quot;,<br>      body: JSON.stringify(<br>          { username: username, password: password })<br>      }).then(response =&gt; {<br>        if (!response.ok) {<br>          throw new Error(&quot;Cannot signup!&quot;);<br>        }<br>        return response.json();<br>      }).then(data =&gt; {<br>        context.commit(&quot;LOGIN&quot;, <br>              { username: username, token: data.token });<br>      }).catch(error =&gt; {<br>        context.commit(&quot;LOGOUT&quot;);<br>        error.read().then((data, done) =&gt; {<br>            throw Error(data);<br>        });<br>      });<br>    }</pre><p>Just note that any action now calls the right API, and then if successfully and if the response is ok it calls the correct mutation with the data returned from the call, else an error is thrown (so the caller of the action can act accordingly).</p><p>Finally, add an additional getter to be used with other api in other stores:</p><pre>getTokenHeader(state) {<br>  return &quot;Bearer &quot; + state.user.token;<br>}</pre><p>Using this getter the other stores will be able to set the correct token for the calls. Let’s just do this for the posts store: this is actually really simple, in the three api we have protected just update the headers parameter of the fetch like the following:</p><pre>headers: {<br>     &quot;Content-Type&quot;: &quot;application/json&quot;,<br>     Authorization: context.rootGetters[&quot;auth/getTokenHeader&quot;]        },</pre><p>Now let’s update the user store too, removing the initialization of the users array in the state and creating an action that can actually call the ADD_USER mutation</p><pre>state: {<br>    loadedUsers: []<br>  },<br>  .....<br>  actions: {<br>    async addUser(context, { username }) {<br>      return fetch(&quot;http://localhost:3000/api/users/&quot; + username, {<br>        headers: {<br>          Authorization: context.rootGetters[&quot;auth/getTokenHeader&quot;]<br>        }<br>      })<br>        .then(response =&gt; {<br>          if (!response.ok) throw new Error(&quot;Cannot get user&quot;);<br>          return response.json();<br>        })<br>        .then(data =&gt; {<br>          context.commit(&quot;ADD_USER&quot;, data);<br>        })<br>        .catch(error =&gt; {<br>          console.log(error);<br>          throw error;<br>        });<br>    }</pre><p>This is actually the same we have already done with the posts.</p><p>These updates will work all by themselves, almost with no updates on the components logic. Now let’s change the login page to actually be a login/signup working page. Update the <em>views/Login.vue </em>component like this:</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;content&quot;&gt;<br>    &lt;base-card&gt;<br>      &lt;form @submit.prevent&gt;<br>        &lt;label for=&quot;username&quot;&gt;Username&lt;/label&gt;<br>        &lt;input id=&quot;username&quot; type=&quot;text&quot; v-model=&quot;username&quot; /&gt;<br>        &lt;label for=&quot;password&quot;&gt;Password&lt;/label&gt;<br>        &lt;input id=&quot;password&quot; type=&quot;password&quot; v-model=&quot;password&quot; /&gt;<br>        &lt;button @click=&quot;loginButtonClicked&quot;&gt;{{ buttonString }}&lt;/button&gt;<br>        &lt;p v-if=&quot;error&quot;&gt;{{ error }}&lt;/p&gt;<br>        &lt;a href=&quot;#&quot; @click.prevent=&quot;toggleLogin&quot;&gt;{{ textLoginString }}&lt;/a&gt;<br>      &lt;/form&gt;<br>    &lt;/base-card&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import { mapActions } from &quot;vuex&quot;;<br>import BaseCard from &quot;../components/UI/BaseCard.vue&quot;;<br>export default {<br>  components: { BaseCard },<br>  data() {<br>    return {<br>      loginSelected: true,<br>      username: &quot;&quot;,<br>      password: &quot;&quot;,<br>      error: &quot;&quot;<br>    };<br>  },<br>  methods: {<br>    ...mapActions({ login: &quot;auth/login&quot;, signup: &quot;auth/signup&quot; }),<br>    loginButtonClicked() {<br>      if (this.loginSelected) {<br>        this.login({ username: this.username, password: this.password })<br>          .then(() =&gt; {<br>            this.$router.push({ name: &quot;Posts&quot; });<br>          })<br>          .catch(error =&gt; {<br>            this.error = error;<br>          });<br>      } else {<br>        this.signup({ username: this.username, password: this.password })<br>          .then(() =&gt; {<br>            this.$router.push({ name: &quot;Posts&quot; });<br>          })<br>          .catch(error =&gt; {<br>            this.error = error;<br>          });<br>      }<br>    },<br>    toggleLogin() {<br>      this.loginSelected = !this.loginSelected;<br>    }<br>  },<br>  computed: {<br>    buttonString() {<br>      if (this.loginSelected) {<br>        return &quot;LOGIN&quot;;<br>      } else {<br>        return &quot;SIGNUP&quot;;<br>      }<br>    },<br>    textLoginString() {<br>      if (this.loginSelected) {<br>        return &quot;Signup instead&quot;;<br>      } else {<br>        return &quot;Login instead&quot;;<br>      }<br>    }<br>  }<br>};<br>&lt;/script&gt;</pre><p>The page will show a login or signup request, and we will store this selection in the “loginSelected” variable, set by the “toggleLogin” method. The login and signup actions are actually bound with mapActions, and the button click event is actually firing the one or the other, looking into the actual “loginSelected” value. So now, when a user does a signup, the actual application authentication store makes a call to the API and will create the new user. The same applies for the login.</p><p>In the User.vue view we can make the call to the addUser in the mounted hook of the component:</p><pre>mounted() {<br>    this.$store.dispatch(&quot;users/addUser&quot;, {username: this.userid});  <br>}</pre><p>when the component is open with a userid it will call the api for the details for this user and add it to the store.</p><p>In the SinglePost component, also, just update the delete button to be shown only for the posts of the actual user, it authenticated, like this:</p><pre>&lt;button        <br>    v-if=&quot;loggedIn &amp;&amp; currentUser.username === post.username&quot;<br>    class=&quot;delete-button&quot;<br>    @click.prevent=&quot;deletePost&quot;&gt;</pre><p>One last update, let’s change a little the application bar, so that when the logout button is clicked it automatically redirect the routing to the login page:</p><pre>logoutButtonClicked() {<br>      this.logout().then(() =&gt; {<br>        this.$router.push({ name: &quot;Login&quot; });<br>      });<br>    }</pre><p>Now the application start to take form, any user can register, add some posts, then delete his own posts, and see other users. Also, we have set up some conditions when the user can perform some actions, and whenever he is not authorized to do it (i.e. we decided that anyone can see the list of the posts, but only logged users can see the other users).</p><p>Note that actually a user is going to be logged out every 15 minutes, one nice way to fix this would be to renew the token in the client automatically and at regular time steps.</p><p>The next important step is to actually use a database instead of an array, server side, to store our data, and then our application would be almost fully working, but before we are going to save the authentication data in indexedDB in the browser of the user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64978f7c381f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social application with Vue.js and GO]]></title>
            <link>https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-d9e563466b66?source=rss-90a990ce37dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9e563466b66</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Ivano Dalmasso]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 09:30:06 GMT</pubDate>
            <atom:updated>2021-04-14T10:57:01.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*9RcvJALOdCOUBieIJCCMEg.jpeg" /><figcaption>Logo credits to vuejs.org and golang.org</figcaption></figure><h4>Create and serve a twitter like application with vue.js and golang PART 7: Connection with GOLANG server</h4><p>This is the seventh part of this serie. Check here all the parts:</p><ul><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4e4db0cdde64">Part1: Setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64b3adee8dac">Part2: Getting started with VUE</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-24a1d1e7137d">Part3: Components &amp; slots</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-3a11d506fc38">Part4: Vuex first setup</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-ef364b572422">Part5: Vuex finalization</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-a22a1afb76eb">Part6: Forms and data in Vuex</a></li><li>Part7: Connection with golang server (this)</li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64978f7c381f">Part8: Token-based authentication</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4d0caa37ddac">Part9: Store authentication token with indexedDB</a></li></ul><p>In this lesson our simple application is starting to finally talk with our golang backend server, we will start writing logic on both frontend for communication and backend to data storage the posts data.</p><p>We will update both the frontend and the backend in this session, you can find the code here:</p><ul><li><a href="https://github.com/idalmasso/go-vue-tutorial-backend/releases/tag/v0.7">backend</a></li><li><a href="https://github.com/idalmasso/go-vue-tutorial-frontend/releases/tag/v0.7">frontend</a></li></ul><h4>Create logic for posts on backend</h4><p>Let’s begin creating some logic on the backend enabling us to manipulate posts. Create a folder “<em>&lt;backend_source_folder&gt;/endpoints</em>” (that actually will translate in creating a package with that same name) and inside it create two files: <em>utils.go </em>and <em>posts.go</em>.</p><p>In the utils.go file insert the following code:</p><pre>package endpoints;</pre><pre>import (<br> &quot;encoding/json&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;github.com/gorilla/mux&quot;<br>)</pre><pre>//AddRouterEndpoints add the actual endpoints for api<br>func AddRouterEndpoints(r *mux.Router) *mux.Router {<br>  r.HandleFunc(&quot;/api/posts&quot;, getPosts).Methods(&quot;GET&quot;)<br>  r.HandleFunc(&quot;/api/posts&quot;, addPost).Methods(&quot;POST&quot;)<br>  r.HandleFunc(&quot;/api/posts/{POST_ID}&quot;,deletePost)<br>      .Methods(&quot;DELETE&quot;)<br>  r.HandleFunc(&quot;/api/posts/{POST_ID}/comments&quot;,addComment)<br>      .Methods(&quot;POST&quot;)<br>  return r<br>}<br><br>func sendJSONResponse(w http.ResponseWriter, data interface{}) {<br>  body, err := json.Marshal(data)<br>  if err != nil {<br>    log.Printf(&quot;Failed to encode a JSON response: %v&quot;, err)<br>    w.WriteHeader(http.StatusInternalServerError)<br>    return<br>  }<br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json; charset=UTF-8&quot;)<br>  w.WriteHeader(http.StatusOK)<br>  _, err = w.Write(body)<br>  if err != nil {<br>    log.Printf(&quot;Failed to write the response body: %v&quot;, err)<br>    return<br>  }<br>}</pre><p>These functions are pretty easy to understand: the first is going to update a router that comes as parameter adding the route resolve methods for adding, getting and deleting posts. As addition, we also add a method to insert a comment to it. We are using gorilla mux, that is actually a multiplexer that makes more easy and organised the code that manages the routes.</p><p>The code of the first function actually just says that if the /api/posts endpoint of our server is called with an http GET method, it should be server with the getPost function (that we haven’t written yet),and following the other ones.</p><p>The second function is going to be an helper function that we’ll use in the routes functions. This is going to take as input an http.ResponseWriter and an empty interface (that could be, as always, almost anything in go) and then it write with the response writer the object serialized as json with an http OK code. Note that if the object is not json-serializable it will return an error.</p><p>With this setup, we are going to insert in the second file the actual functions that have to handle the routes. At the top of the file we insert</p><pre>package endpoints<br><br>import (<br>	&quot;encoding/json&quot;<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>	&quot;strconv&quot;<br>	&quot;time&quot;<br><br>	&quot;github.com/gorilla/mux&quot;<br>)<br>type comment struct {<br>	ID       int      `json:&quot;id&quot;`<br>	Username string   `json:&quot;username&quot;`<br>	Post string   	  `json:&quot;post&quot;`<br>	Date time.Time 	  `json:&quot;date&quot;`	<br>}<br>//post Struct is used as post structure...<br>type post struct {<br>	ID   		 int       `json:&quot;id&quot;`<br>	Username string    `json:&quot;username&quot;`<br>	Post string    		 `json:&quot;post&quot;`<br>	Date time.Time 		 `json:&quot;date&quot;`<br>	Comments []comment `json:&quot;comments&quot;`<br>}<br></pre><p>This is the definition of two structs, one with name comment and the other with name post, containing the fields we need for the data transmission of the APIs. Note that the field names are all capitalized, that is needed for the json-serialization. We are not going to use a database right by now, we’ll add it in a future lesson, now we’ll just create an array of posts and use them in memory:</p><pre>var posts []post=make([]post, 0)<br>//need an index for the array... When I&#39;ll delete the posts the index will have to go on...<br>var index int=1<br></pre><p>After this we can start creating the actual handler functions:</p><pre>//addPost will get in Body a post with ONLY username and post-&gt; need to add the others and save it<br>func addPost(w http.ResponseWriter, r *http.Request) {<br>  log.Println(&quot;addPost called&quot;)<br>  var actualPost post<br>  err:=json.NewDecoder(r.Body).Decode(&amp;actualPost)<br>  if err!=nil{<br>    http.Error(w, err.Error(), http.StatusBadRequest)<br>    return<br>  }<br>  actualPost.ID = index<br>  index++<br>  actualPost.Date=time.Now()<br>  if actualPost.Comments== nil{<br>    actualPost.Comments=make([]comment, 0)<br>  }<br>  posts=append(posts, actualPost)<br>  sendJSONResponse(w,actualPost)<br>}</pre><pre>//deletePost removes the post that is being passed. Get the id from //the query<br>func deletePost(w http.ResponseWriter, r *http.Request) {<br>  log.Println(&quot;deletePost called&quot;)<br>  vars := mux.Vars(r)<br>  idString, ok := vars[&quot;POST_ID&quot;]<br>  if !ok {<br>    http.Error(w, &quot;Cannot find ID&quot;, http.StatusBadRequest)<br>    return<br>  }<br>  id, err := strconv.Atoi(idString)<br>  if err!=nil{<br>    http.Error(w, &quot;Cannot convert the id value to string&quot;,http.StatusBadRequest)<br>    return<br>  }<br>  for i:=0;i&lt;len(posts);i++{<br>    if posts[i].ID==id {<br>      posts[i]=posts[len(posts)-1]<br>      posts=posts[:len(posts)-1]<br>      w.WriteHeader(http.StatusOK)<br>      return<br>    }<br>  }<br>  http.Error(w, &quot;Cannot find the requested id&quot;, http.StatusNotFound)<br>}<br>//addComment will get the comment in the body, and the id in the query<br>func addComment(w http.ResponseWriter, r *http.Request) {<br>  log.Println(&quot;addComment called&quot;)<br>  vars := mux.Vars(r)<br>  idString, ok := vars[&quot;POST_ID&quot;]<br>  if !ok {<br>    http.Error(w, &quot;Cannot find ID&quot;, http.StatusBadRequest)<br>    return<br>  }<br>  id, err := strconv.Atoi(idString)<br>  if err!=nil{<br>    http.Error(w, &quot;Cannot convert the id value to string&quot;, http.StatusBadRequest)<br>    return<br>  }<br>  var actualComment comment<br>  err = json.NewDecoder(r.Body).Decode(&amp;actualComment)<br>  if err!=nil{<br>    http.Error(w, err.Error(), http.StatusBadRequest)<br>    return<br>  }<br>  for i:=0;i&lt;len(posts);i++{<br>    if posts[i].ID==id {<br>      //Now I have the post<br>      var commMax int=0<br>      for comm:=0;comm&lt;len(posts[i].Comments);comm++{<br>        if commMax&lt;posts[i].Comments[comm].ID{<br>          commMax=posts[i].Comments[comm].ID<br>        }<br>      }<br>      actualComment.ID=commMax+1<br>      actualComment.Date=time.Now()<br>      posts[i].Comments = append(posts[i].Comments, actualComment)<br>      sendJSONResponse(w, posts[i])<br>      return<br>    }<br>  }<br>  //If I&#39;m here, there is no post with the id searched... <br>  http.Error(w, &quot;Cannot find a post with the selected id&quot;, http.StatusNotFound)<br>}<br>//getPosts will return all the posts actually in the array<br>func getPosts(w http.ResponseWriter, r *http.Request) {<br>  log.Println(&quot;Get post called&quot;)<br>  sendJSONResponse(w, posts)<br>}</pre><p>Let’s explain this code:</p><ul><li>The addPost function actually just try to decode the request body as a Post object. If this can be done, it adds this object, with a populated id and date, to our posts “storage”, and then returns it back, updated, with an ok response</li><li>The deletePost function gets the POST_ID query parameter, and if there is a post in the “storage” with that id, it gets deleted. Else, it returns a NotFound status code to the client.</li><li>The addComment adds a comment object passed (if decoded successfully) to the post indicated by the POST_ID query parameter. Actually the code for looking up the ID is not nice at all, but as soon as we’ll start using a database we’ll replace it.</li><li>The getPosts just write as answer the list of posts serialized as json.</li></ul><p>Now all objects can be called, the last thing to do is to call in the main function of the server the <em>addRouterEndpoint </em>method wrote before in the utils file. Then, to manage the CORS policies, we just write a simple decorator that will be applied to the router before passing it to the http.Handle function. This is simply done like this:</p><pre>func main(){<br>  r := mux.NewRouter()<br>  r=endpoints.AddRouterEndpoints(r)<br>  fs := http.FileServer(http.Dir(&quot;./dist&quot;))<br>  r.PathPrefix(&quot;/&quot;).Handler(fs)<br>	<br>  http.Handle(&quot;/&quot;,&amp;corsRouterDecorator{r})<br>  fmt.Println(&quot;Listening&quot;)	<br>  log.Panic(<br>    http.ListenAndServe(&quot;:3000&quot;, nil),<br>  )<br>}<br><br><br>type corsRouterDecorator struct {<br>  R *mux.Router<br>}<br><br>func (c *corsRouterDecorator) ServeHTTP(rw http.ResponseWriter, req *http.Request) {<br>  if origin := req.Header.Get(&quot;Origin&quot;); origin != &quot;&quot; {<br>    rw.Header().Set(&quot;Access-Control-Allow-Origin&quot;, origin)<br>    rw.Header().Set(&quot;Access-Control-Allow-Methods&quot;, <br>      &quot;POST, GET, PUT, DELETE, PATCH&quot;)<br>    rw.Header().Add(&quot;Access-Control-Allow-Headers&quot;, <br>      &quot;Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With&quot;)<br>  }<br>  // Stop here if its Preflighted OPTIONS request<br>  if req.Method == &quot;OPTIONS&quot; {<br>    return<br>  }<br>  c.R.ServeHTTP(rw, req)<br>}</pre><p>That’s it! with this, we have the 4 wanted routes created and served by this server, that will then manipulate the posts and comment objects. Note that in this chapter we’re not going to manage the authentication, so any user that will send a post to the /api/posts POST route will be able to add a new post to our server. We will do that in another chapter.</p><h4>Updating the frontend</h4><p>In the frontend most of the work is going to be done in the store actions. Note that we changed in backend the “post.user” to “post.username”, so just for semplicity let’s change it anywhere.</p><p>Then, in the index.js of the Post store, let’s make some modification. As first, we won’t have anymore an “ADD_COMMENT” mutation but, because the route returns us the complete post object, we can instead have a “SET_POST_COMMENTS” mutation like this:</p><pre>SET_POST_COMMENTS(state, { postId, post }) {<br>  const oldPost = state.posts.find(post =&gt; post.id == postId);<br>  oldPost.comments = post.comments;<br>}</pre><p>then, the ADD_POST mutation doesn’t need to find an id anymore, so it can become more simple. Also, let’s add a SET_ALL_POSTS mutation for initialization:</p><pre>ADD_POST(state, post) {<br>  state.posts.push(post);<br>},<br>SET_ALL_POSTS(state, posts) {<br>  state.posts = posts;<br>},</pre><p>WIth this we have changed and simplified our mutations. We can now update the actions to call the api too and add the new action “getAllPosts” to complete the functionalities we need. This is done with the following code:</p><pre>async addPost(context, post) {<br>      fetch(&quot;http://localhost:3000/api/posts&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>        body: JSON.stringify(post)<br>      })<br>        .then(response =&gt; {<br>          if (!response.ok) {<br>            throw Error(response.body);<br>          }<br>          return response.json();<br>        })<br>        .then(data =&gt; {<br>          context.commit(&quot;ADD_POST&quot;, data);<br>        })<br>        .catch(error =&gt; {<br>          console.log(error);<br>        });<br>    },<br>    async deletePost(context, { post }) {<br>      fetch(&quot;http://localhost:3000/api/posts/&quot; + post.id, {<br>        method: &quot;DELETE&quot;<br>      })<br>        .then(response =&gt; {<br>          if (response.ok) {<br>            console.log(response);<br>            context.commit(&quot;DELETE_POST&quot;, post.id);<br>            return;<br>          }<br>          throw Error(response);<br>        })<br>        .catch(error =&gt; {<br>          console.log(error);<br>        });<br>    },<br>    async addComment(context, { postId, comment }) {<br>      fetch(&quot;http://localhost:3000/api/posts/&quot; + postId + &quot;/comments&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;<br>        },<br>        body: JSON.stringify(comment)<br>      })<br>        .then(response =&gt; {<br>          if (response.ok) {<br>            return response.json();<br>          } else throw Error(response.body);<br>        })<br>        .then(data =&gt; {<br>          context.commit(&quot;SET_POST_COMMENTS&quot;, { postId: postId, post: data });<br>        })<br>        .catch(error =&gt; {<br>          console.log(error);<br>        });<br>    },<br>    async getAllPosts(context) {<br>      fetch(&quot;http://localhost:3000/api/posts&quot;)<br>        .then(response =&gt; {<br>          if (response.ok) {<br>            return response.json();<br>          } else {<br>            throw Error(response.body);<br>          }<br>        })<br>        .then(data =&gt; {<br>          console.log(data);<br>          context.commit(&quot;SET_ALL_POSTS&quot;, data);<br>        })<br>        .catch(error =&gt; {<br>          console.log(error);<br>        });<br>    }</pre><p>So, all these actions actually calls with a fetch the new relative api we created on the server. In the resolution of the returned promises, if the response is ok, we call the commit of the mutation, else we just console.log the error. Obviously when the promise resolution has an object parameter that we must later use, we have to deserialize it, and this is done really easily with the promise resolution of the response.json() method. With that we could then also send the data to the mutations we have to commit.</p><p>Note that we have never added a delete button for the posts, so let’s just do it now: in the SinglePost component, add in the slot header of the card a normal button like</p><pre>&lt;button class=&quot;delete-button&quot; @click.prevent=&quot;deletePost&quot;&gt;        Delete<br>&lt;/button&gt;</pre><p>And the logic behind it is pretty easy, we must dispatch the detetePost action with the post value:</p><pre>deletePost() {<br>  this.$store.dispatch(&quot;posts/deletePost&quot;, { post: this.post });    }</pre><p>Now we need only to initialize the Posts store.</p><p>We can do it in the Posts.vue component, using the mounted() configuration method like this:</p><pre>mounted() {    <br>  this.$store.dispatch(&quot;posts/getAllPosts&quot;);<br>  }</pre><p>Like this,when the posts component is mounted, it calls the getAllPosts action of the store, that fills the store with all the posts from the server. Then, every action in the vue user interface calls the relative action of the store, and the update of the store automatically is reflected in the components.</p><p>The fact that the actions are async, permits to do some action when they resolve (so, for example, we could set a waiting gif or animation when the user click on delete post, and remove the animation when the action resolve).</p><p>With this setup, we can then launch the server, and after the vue client, and then everything should work fine, with the posts that are actually added to the backend storage.</p><p>We have actually still two big problems to solve:</p><ol><li>The posts are actually maintained in memory, this will be solved in next lessons, right by now if we stop the server the posts are actually lost forever, but at least the client is now persistent, and also reopening the page will show again the data.</li><li>The authentication, now any user can store a new post, by passing a post object to the server.</li></ol><p>With the next chapter we are going to address this last problem, so only an authenticated user will be able to login and use the actual application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9e563466b66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social application with Vue.js and GO]]></title>
            <link>https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-a22a1afb76eb?source=rss-90a990ce37dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a22a1afb76eb</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Ivano Dalmasso]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 14:22:12 GMT</pubDate>
            <atom:updated>2021-04-14T10:57:10.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*9RcvJALOdCOUBieIJCCMEg.jpeg" /><figcaption>Logo credits to vuejs.org and golang.org</figcaption></figure><h4>Create and serve a twitter like application with vue.js and golang PART 6: Forms and data in VUEX</h4><p>This is the sixth part of this serie. Check here all the parts:</p><ul><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4e4db0cdde64">Part1: Setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64b3adee8dac">Part2: Getting started with VUE</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-24a1d1e7137d">Part3: Components &amp; slots</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-3a11d506fc38">Part4: Vuex first setup</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-ef364b572422">Part5: Vuex finalization</a></li><li>Part6: Forms and data in Vuex (this)</li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-d9e563466b66">Part7: Connection with golang server</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64978f7c381f">Part8: Token-based authentication</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4d0caa37ddac">Part9: Store authentication token with indexedDB</a></li></ul><p>In this chapter we are going to finally create some forms so we can use the store previously created and insert/update there some data. Note that at the end of this part we’ll have an application that have a client side in-memory storage, where we can add and update values. Also, we won’t have a persistent data layer, yet: for that, we’ll have to wait some more lessons.</p><p>Main target here is to update the frontend project, you can find the code <a href="https://github.com/idalmasso/go-vue-tutorial-frontend/releases/tag/v0.6">here</a>.</p><h4>Updates to the store</h4><p>Before inserting the actual forms, let’s make some last updates to the post store so that can accept the insertion of posts and also comments.</p><p>As first, remove all the post objects in the list in the state, so it will start as an empty array. Then, update the ADD_POST mutation to also have some logic to populate the id for the post (remember: when there will be a working backend this won’t be used anymore), and also add a mutation for adding a comment to a post, like this:</p><pre>ADD_POST(state, post) {<br>      if (state.posts.length &lt; 1) {<br>        post.id = 1;<br>      } else {<br>        const max = state.posts.reduce((prev, current) =&gt;<br>          prev.id &gt; current.id ? prev : current<br>        );<br>        post.id = max.id + 1;<br>      }<br>      post.comments = [];<br>      state.posts.push(post);<br>    },</pre><pre>ADD_COMMENT(state, { postId, comment }) {<br>      const post = state.posts.find(post =&gt; post.id === postId);<br>      if (post.comments.length &lt; 1) {<br>        comment.id = 1;<br>      } else {<br>        const max = post.comments.reduce((prev, current) =&gt;<br>          prev.id &gt; current.id ? prev : current<br>        );<br>        comment.id = max.id + 1;<br>      }<br>      post.comments.push(comment);<br>    }<br></pre><p>The code here is pretty straight forward. It assigns an id to every post inserted, incremental. And the second mutation does the same for the comments. In the actions, before calling the ADD_POST mutation also insert the date of the post, and also create an action that can do the same with a comment and call the respective mutation:</p><pre>async addPost(context, post) {<br>      post.date = getFormattedDate();<br>      context.commit(&quot;ADD_POST&quot;, post);<br>},<br>async addComment(context, { postId, comment })<br>{<br>      comment.date = getFormattedDate();<br>      context.commit(&quot;ADD_COMMENT&quot;, { postId, comment });<br>}</pre><p>The “<em>getFormattedDate</em>” function is actually a utility function I created before in the same file, just to add a nicely formatted date to both the posts and the comments.</p><h4>Update the posts views</h4><p>Now that we have a store that can add posts and comments, we have to actually use these new functionalities in the components.</p><p>Let’s add a new component that could be used for inputting a single text, and that could also be reusable. Add a new file <em>AddTextForm.vue</em> in the <em>src/components</em> folder, and fill it with the following:</p><pre>&lt;template&gt;<br>  &lt;form&gt;<br>    &lt;label v-if=&quot;showLabel&quot; :for=&quot;&#39;text&#39; + this._uid&quot;&gt;<br>     {{ textRequest }}&lt;/label&gt;<br>    &lt;input<br>      :id=&quot;&#39;text&#39; + this._uid&quot;<br>      type=&quot;text&quot;<br>      :placeholder=&quot;textRequest&quot;<br>      v-model=&quot;textValue&quot;<br>    /&gt;<br>    &lt;button @click.prevent=&quot;submitted&quot;&gt;submit&lt;/button&gt;<br>  &lt;/form&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  data() {<br>    return {<br>      textValue: &quot;&quot;<br>    };<br>  },<br>  props: {<br>    textRequest: { type: String, default: &quot;&quot; },<br>    showLabel: { type: Boolean, default: false }<br>  },<br>  methods: {<br>    submitted() {<br>      this.$emit(&quot;text-added&quot;, this.textValue);<br>      this.textValue = &quot;&quot;;<br>    }<br>  },<br>  emits: [&quot;text-added&quot;]<br>};<br>&lt;/script&gt;<br><br>&lt;style scoped&gt;<br>label {<br>  padding-right: 1rem;<br>  display: block;<br>}<br>button {<br>  margin-top: 1rem;<br>  width: 10%;<br>  border-top-right-radius: 8px;<br>  border-bottom-right-radius: 8px;<br>  background-color: darksalmon;<br>  padding: 8px;<br>}<br>input {<br>  box-sizing: border-box;<br>  border-top-left-radius: 8px;<br>  border-bottom-left-radius: 8px;<br>  width: 80%;<br>  padding: 8px 20px;<br>}<br>input:focus {<br>  outline: 0;<br>  background-color: wheat;<br>}<br>&lt;/style&gt;</pre><p>Here everything should be almost clear: we used a pair of props, one to decide if show the label in the form, the other to decide the placeholder of the textbox to be shown.</p><p>The only new thing we have in this file is actually the use of the “<em>v-model</em>” directive, that is used in conjunction with input fields to connect the value actually in the input to a variable in the data of the component, in a reactive way.</p><p>At the clicked event of the button, the method called emits an event “<em>text-added</em>” to any parent component that use this one. Also, note that we implemented a “<em>emits</em>” configuration parameters, to let the parent know, this is not mandatory but a nice best practice to have.</p><p>This event emitting give us the second communication way between components in vue, the first one being the “<em>props</em>”, so we can send data from parent to child and the other way around.</p><p>With this, any component that use the AddTextForm will be able to listen to the event “<em>text-added</em>” and will get also the data inserted.</p><p>So, right now, let’s use this form to add some posts in the Posts.vue component. Update the template, like this</p><pre>&lt;div class=&quot;posts&quot;&gt;<br>    &lt;h1&gt;All Posts&lt;/h1&gt;<br>    &lt;add-text-form<br>      textRequest=&quot;Add Post&quot;<br>      v-if=&quot;loggedIn&quot;<br>      :showLabel=&quot;true&quot;<br>      @text-added=&quot;addPost&quot;<br>    &gt;&lt;/add-text-form&gt;<br>    &lt;post-list :posts=&quot;posts&quot; title=&quot;&quot; /&gt;<br>  &lt;/div&gt;</pre><p>So, it is all like before, but we added a little title and the new component. We show this component only if the user is logged in, we show a label “Add Post” and on the event “text-added” we call the addPost method. This is actually pretty easy:</p><pre>methods: {<br>    addPost(text) {<br>      this.$store.dispatch(&quot;posts/addPost&quot;, {<br>        user: this.$store.getters[&quot;auth/currentUser&quot;].username,<br>        post: text<br>      });<br>    }<br>  }</pre><p>So, this just dispatch the addPost post, passing the actual authenticated user username and the text post. This will be used from the action, and add the post to the actual store.</p><p>Next natural step is to use the same add-text-form to also add the comments to a post. This can be done in two steps. First we have to change the BaseCard template, so it can also have some “actions” slot, where we can insert some other code. This is easily done adding this after the footer:</p><pre>&lt;div class=&quot;actions&quot;&gt;<br>   &lt;slot name=&quot;actions&quot;&gt;&lt;/slot&gt;<br>&lt;/div&gt;</pre><p>and then we can use this slot in the SinglePost component adding the following lines after the footer just before the closing tag of the BaseCard:</p><pre>&lt;template v-if=&quot;loggedIn&quot; v-slot:actions&gt;<br>   &lt;add-text-form<br>        textRequest=&quot;Add comment&quot;<br>        :showLabel=&quot;false&quot;<br>        @text-added=&quot;text =&gt; addComment(text, post)&quot;&gt;<br>    &lt;/add-text-form&gt;<br>&lt;/template&gt;</pre><p>Note that for this we have to add a mapGetter to the loggedIn getter of the store to render the button only if the user is actually logged in.</p><p>On the emission of the event “text-added”, it’s called a function <em>addComment</em>, that we have to add to the methods like this:</p><pre>addComment(text, post) {<br>      this.$store.dispatch(&quot;posts/addComment&quot;, <br>          {<br>             postId: post.id,<br>             comment: <br>             {<br>                user: this.currentUser.username,<br>                post: text<br>            }<br>      });</pre><p>This will obviously add the comment to the store, and so every other page will be able to load it when needed.</p><h4>Add a login page</h4><p>Right by now the login button is only swapping the login status of the actual user from “logged in” to “not logged in”. In the future the user will have to actually request a login via a user/password form, so just now let’s create a login page that will do this. For now it’s going to be a placeholder, with only a “login” button, but it will be soon completed with the other functionalities.</p><p>In the view folders, create a Login.vue file with thw following:</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;login&quot;&gt;<br>    &lt;button @click=&quot;loginButtonClicked&quot;&gt;LOGIN&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import { mapActions } from &quot;vuex&quot;;<br>export default {<br>  methods: {<br>    ...mapActions({ login: &quot;auth/login&quot; }),<br>    loginButtonClicked() {<br>      this.login().then(() =&gt; {<br>        this.$router.push({ name: &quot;Posts&quot; });<br>      });<br>    }<br>  }<br>};<br>&lt;/script&gt;<br><br>&lt;style scoped&gt;<br>button {<br>  margin-top: 1rem;<br>  width: 20rem;<br>  height: 5rem;<br>  border-radius: 8px;<br>  background-color: darksalmon;<br>  padding: 8px;<br>}<br>&lt;/style&gt;</pre><p>Nothing new here, only note the “<em>router.push</em>” instruction that will redirect the browser to the Posts view after the login store action has been succesfully completed.</p><p>To complete this step, we have only to change the application bar now, that must navigate to the login view when the login button is pressed. To do so, just change a little the login link, from a “<em>a</em>” tag to a router-link that goes to the Login view:</p><pre>&lt;router-link<br>        class=&quot;app-bar-item&quot;<br>        href=&quot;#&quot;<br>        v-if=&quot;!loggedIn&quot;<br>        @click.prevent :to=&quot;{ name: &#39;Login&#39; }&quot;LOGIN        &gt;LOGIN&lt;/router-link&gt;</pre><p>Also, to complete this update, we can make sure that when a user logs out of the application goes to the login page automatically, attaching this new method to the logout link clicked event:</p><pre>logoutButtonClicked() {<br>      this.logout().then(() =&gt; {<br>        this.$router.push({ name: &quot;Login&quot; });<br>      });<br>    }</pre><p>Last thing to do, update the router file to add the new “Login” route, like this:</p><pre>import Login from &quot;../views/Login.vue&quot;;</pre><pre>...<br>{<br>     path: &quot;/login&quot;,   <br>     name: &quot;Login&quot;,    <br>     component: Login<br>}</pre><h4>Add some navigation guards on login status</h4><p>We would like the user to not being able to go in some pages if the user is not logged in (for example, the User page). So, as first thing, we can go to the application bar component, and show only some links if the user is not enabled: in the template change the actually present <em>v-for=”link in links” </em>to <em>v-for=”link in activeLinks”</em>, and also add the <em>activeLinks </em>computed method as:</p><pre>activeLinks() {<br>      return this.links.filter(<br>        link =&gt; link.visibleIfLoggedOut || this.loggedIn<br>      );<br>    }</pre><p>With this the links shown are only the ones that can be visible if the user is logged out, or if the user is logged in. We should also add the property “<em>visibleIfLoggedOut</em>” to the links, like this:</p><pre>links: [<br>        {<br>          visibleIfLoggedOut: true,<br>          name: &quot;Posts&quot;,<br>          to: { name: &quot;Posts&quot; }<br>        },<br>        {<br>          visibleIfLoggedOut: false,<br>          name: &quot;User&quot;,<br>          to: {<br>            name: &quot;User&quot;,<br>            params: {<br>              userid: this.$store.getters[&quot;auth/currentUser&quot;].username<br>            }<br>          }<br>        }</pre><p>This code actually hides the link of “User” if the user is logged out, but this is actually not all we need to do. In fact, if a user puts the url of the User page in the address bar of the browser, the page will be seen. We need to make sure that the router makes some kind of processing to decide if a user can or cannot view some pages, in this case.</p><p>This is actually done via navigation guards: these are some configuration methods that can be used to instruct the router about things to do before and after a navigation event has called.</p><p>These can be set at route or at global level, in this case for example we are going to set a navigation guard on the User route, telling that if the user is not actually logged it should instead be routed to the login page. In the same way, we would like that an already logged in user should not go to the login page, and instead be redirected, for example, to the posts page.</p><p>In the router file, update the two routes like this:</p><pre>import store from &quot;@/store/index.js&quot;;<br>...<br>  {<br>    path: &quot;/user/:userid&quot;,<br>    name: &quot;User&quot;,<br>    component: User,<br>    props: true,<br>    beforeEnter: (to, from, next) =&gt; {<br>      if (!store.getters[&quot;auth/isLoggedIn&quot;]) {<br>        next({ name: &quot;Login&quot; });<br>      } else {<br>        next();<br>      }<br>    }<br>  },<br>  {<br>    path: &quot;/login&quot;,<br>    name: &quot;Login&quot;,<br>    component: Login,<br>    //This is not needed right by now, because the store is  refreshed on page refresh... Will be needed!<br>    beforeEnter: (to, from, next) =&gt; {<br>      if (store.getters[&quot;auth/isLoggedIn&quot;]) {<br>        next({ name: &quot;Posts&quot; });<br>      } else {<br>        next();<br>      }<br>    }<br>  }</pre><p>The beforeEnter configuration is actually a function that has as input three parameters:</p><ol><li>to: the target <a href="https://router.vuejs.org/api/#the-route-object">Route Object</a> being navigated to.</li><li>from: the current route being navigated away from</li><li>next: a function that resolve the navigation. When it is called, depending on the parameter passed to it the resolution will be different: if no parameters will be passed, the resolution will be the normal one, if we pass it a route object, this will be pushed in the history of the browser (in our case, we will go there, instead of the normal route).</li></ol><p>So, in our case, we can have the behaviour we wanted before for these two routes. Obviously, nothing block a malicious user to force a request, if he really want, so always remember to duplicate all “security” controls on backend too!</p><p>Now, we have reached an almost stop point in the frontend, and so next step is going to start adding a go backend that will serve some api with the actual posts, and authentication features that we will need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a22a1afb76eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social application with Vue.js and GO]]></title>
            <link>https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-ef364b572422?source=rss-90a990ce37dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef364b572422</guid>
            <dc:creator><![CDATA[Ivano Dalmasso]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 11:30:59 GMT</pubDate>
            <atom:updated>2021-04-14T10:57:15.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*9RcvJALOdCOUBieIJCCMEg.jpeg" /><figcaption>Logo credits to vuejs.org and golang.org</figcaption></figure><h4>Create and serve a twitter like application with vue.js and golang PART 5: VUEX finalization</h4><p>This is the fifth part of this serie. Check here all the parts:</p><ul><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4e4db0cdde64">Part1: Setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64b3adee8dac">Part2: Getting started with VUE</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-24a1d1e7137d">Part3: Components &amp; slots</a></li><li><a href="https://medium.com/nerd-for-tech/social-application-with-vue-js-and-go-3a11d506fc38">Part4: Vuex first setup</a></li><li>Part5: Vuex finalization (this)</li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-a22a1afb76eb">Part6: Forms and data in Vuex</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-d9e563466b66">Part7: Connection with golang server</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64978f7c381f">Part8: Token-based authentication</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4d0caa37ddac">Part9: Store authentication token with indexedDB</a></li></ul><p>In this lesson we are going to update the vuex store, we will have a better logic to maintain the authentication of the user. Then we will update the application to use the vuex store we have created</p><p>Main target here is to update the frontend project, you can find the code <a href="https://github.com/idalmasso/go-vue-tutorial-frontend/releases/tag/v0.5">here</a>.</p><h4>Improve the vuex store</h4><p>In this first part, we change a little the vuex store we wrote in last lesson. What we want to do is to remove the login and logout logic from the User store, that will then only contain the list of users data, and put it into another store, only for authentication purposes.</p><p>So just create a folder “<strong>src/store/authStore</strong>” and move inside it the code bound to the authentication that was previously in the User store:</p><pre>export default {<br>  namespaced: true,<br>  state: {<br>    user: {<br>      id: 1,<br>      username: &quot;idalmasso&quot;,<br>      description: &quot;Here is the description&quot;,<br>      //here there will be the logic for auth and so on...<br>      loggedIn: false<br>    }<br>  },<br>  mutations: {<br>    LOGIN(state) {<br>      state.user.loggedIn = true;<br>    },<br>    LOGOUT(state) {<br>      state.user.loggedIn = false;<br>    }<br>  },<br>  actions: {<br>    async login(context) {<br>      context.commit(&quot;LOGIN&quot;);<br>    },<br>    async logout(context) {<br>      context.commit(&quot;LOGOUT&quot;);<br>    }<br>  },<br>  getters: {<br>    currentUser(state) {<br>      return state.user;<br>    },<br>    isLoggedIn(state) {<br>      if (!state.user) return false;<br>      return state.user.loggedIn;<br>    }<br>  }<br>};</pre><p>Just a little refactoring in this, the code is the same as before. Now the Users store can also be changed like this:</p><pre>export default {<br>  namespaced: true,<br>  state: {<br>    loadedUsers: [<br>      {<br>        id: 1,<br>        username: &quot;idalmasso&quot;,<br>        description: &quot;Here is the description&quot;,<br>        //here there will be the logic for auth and so on...<br>        loggedIn: false<br>      }<br>    ]<br>  },<br>  mutations: {<br>    ADD_USER(state, user) {<br>      if (state.loadedUsers.some(u =&gt; u.username == user.username)) {<br>        state.loadedUsers.splice(<br>          state.loadedUsers.indexOf(u =&gt; u.username == user.username),<br>          1<br>        );<br>      }<br>      state.loadedUsers.push(user);<br>    }<br>  },<br>  actions: {},<br>  getters: {<br>    getUser: state =&gt; userid =&gt; {<br>      if (state.loadedUsers.some(user =&gt; user.username == userid)) {<br>        return state.loadedUsers.find(user =&gt; user.username == userid);<br>      } else {<br>        //Here I&#39;ll have to request from the server!!<br>        return {};<br>      }<br>    }<br>  }<br>};</pre><p>where we have removed the authentication code, and just added the ADD_USER mutation, that will let us to add a user to the array in the state data, and added a getter “getUser”: this returns a function that from the <em>userid </em>returns the respective user from the store. We used the username as id for simplicity here, in a real application probably you would prefer to use an id of some sort.</p><p>Just note that in this application we are going to insert in the store all the users and all the posts from the database everytime. This is also only for simplicity, in real applications you would want to fetch from the server and maintain only some of the data (i.e. the most recent posts of people you follow, the last viewed users, etc.)</p><p>As last, remember to add the import module in the general index.js store file, in “<strong>src/store/index.js</strong>”.</p><h4>Change the components to reflect the store changes</h4><p>As first, having the Users store now containing the users, we can change the router to make sure that it can show the User component with different username parameter. To do this, just change the path of the User route from “<strong>/user</strong>” to “<strong>/user/:userid</strong>”. Doing this way, the userid will be passed as prop to the user component, and will also be present in the url, so if a user would like to “share” a page, for whatever reason, he could go and just copy and paste the link.</p><p>Now, in the User component, we can add the props configuration:</p><pre>props: {<br> userid: { type: String, default: “” }<br> },</pre><p>And then change the “<em>user</em>” computed method to return the user from the store like this:</p><pre><br>return this.$store.getters[“users/getUser”](this.userid);</pre><p>This will get the function “<em>getUser</em>” from the store getters and call it with parameter “<em>this.userid</em>”.</p><p>Now, we’d like to change the requests to this route to include this <em>userid </em>parameter.</p><p>The first place where we want to change this is in the applicatin bar. This is actually pretty straightforward: we have just to change in the data configuration option the link to the user view, and make it have a userid parameter. This is easily done by doing this:</p><pre>links: [<br>       ...<br>        {<br>          name: &quot;User&quot;,<br>          to: {<br>            name: &quot;User&quot;,<br>            params: {<br>              userid: this.$store.getters[&quot;auth/currentUser&quot;].username<br>            }<br>          }<br>        }<br>      ]</pre><p>This code gets the parameters data from the “<em>currentuser</em>” getter of the <em>auth </em>store, and use it for the routing to the User component. Pretty easy right?</p><p>Now it is possible to expand this thing a little, and make sure that all posts headers become links to the user who wrote the actual post. We do this in SinglePost component, as first simply add a “<em>linkUser</em>” method like this:</p><pre>linkUser(username) {<br>      return {<br>        name: &quot;User&quot;,<br>        params: {<br>          userid: username<br>        }<br>      };<br>    }</pre><p>This method builds the link object requested by the router, so it can navigate to the correct page using a username parameter. In this way we only have to make a little change to the title of the card in the template to get this working, changing the call to the header template of the post in this</p><pre>&lt;template v-slot:header&gt;<br>      &lt;h3&gt;<br>        &lt;router-link :to=&quot;linkUser(post.user)&quot;&gt;<br>         {{ postTitle(post)}}<br>        &lt;/router-link&gt;<br>      &lt;/h3&gt;<br>&lt;/template&gt;</pre><p>This will update the title of each post to be a link to the user page. It’s easy to update also the comment title in the same way, in the comment card:</p><pre>&lt;template v-slot:header&gt;<br>          &lt;h3&gt;<br>            &lt;router-link :to=&quot;linkUser(comment.user)&quot;&gt;<br>             {{ postTitle(comment)}}<br>            &lt;/router-link&gt;<br>          &lt;/h3&gt;<br>&lt;/template&gt;</pre><p>As you can see the code is almost the same, just because we kept the structure of comment and post objects really similar.</p><p>Now you can try to play with the store, add some user in the User store data object, some post of these users in the Posts store, and see that the links actually works correctly. Also, the link in the application bar will route you to the User page of the user in the auth store.</p><p>As last thing, let’s start to add a little functionality in the application bar to make use of the authentication store.</p><p>We added in the last lessons a “LOGIN” button, that didn’t do anything at all. Now add a couple of methods in the applicationbar component that manage to simulate a login/logout functions:</p><pre>login() {<br> this.$store.dispatch(&quot;auth/login&quot;);<br>},<br>logout() {<br>  this.$store.dispatch(&quot;auth/logout&quot;);<br>}</pre><p>and a computed method that tells us if the current user is actually logged in:</p><pre>loggedIn() {<br>  return this.$store.getters[&quot;auth/isLoggedIn&quot;];<br>}</pre><p>We can use these to display and get the login/logout behaviour in the template, changing the LOGIN button we had previously to this:</p><pre>&lt;div class=&quot;right-links &quot;&gt;<br>      &lt;a class=&quot;app-bar-item&quot; href=&quot;#&quot; v-if=&quot;!loggedIn&quot; @click.prevent=&quot;login&quot;&gt;LOGIN&lt;/a&gt;<br>      &lt;a class=&quot;app-bar-item&quot; href=&quot;#&quot; v-if=&quot;loggedIn&quot; @click.prevent=&quot;logout&quot;&gt;LOGOUT&lt;/a&gt;<br>&lt;/div&gt;</pre><p>This template shows the LOGIN button if the loggedIn computed method is false, else shows the LOGOUT button. The @click is the normal v-on handler for events that we saw previously.</p><p>The .prevent prefix on the handler actually is a modifier that makes sure that if there is some “standard” behaviour that would be called, it is not, so if for example this button would be a submit button on a form, the click of the button wouldn’t trigger a get request and so also the refresh of the page from the server (in this actual case this .prevent is not needed).</p><p>So now when the LOGIN button is pressed, the authentication action is performed asynchronously and when the state actually change, the getter method, that is reactive, will change the value of the computed property, used for define the behaviour of the page, hide the LOGIN button and show the LOGOUT one.</p><p>We actually added a couple of methods, login and logout, and a computed property, isLoggedIn, that are exactly wrappers of actions and getters of the store. This is a common procedure, so vuex has some helpers function to make this easier, mapGetters and mapActions.</p><p>So we can make one last change, this does not change the behaviour of the application but only makes the code more clear and compact: just import the two functions before the export of the applicationBar component:</p><pre>&lt;script&gt;<br>import { mapGetters } from &quot;vuex&quot;;<br>import { mapActions } from &quot;vuex&quot;;<br>export default {<br>...</pre><p>Now use these helpers in the configuration options like this:</p><pre>methods: {<br>    ...mapActions({<br>      login: &quot;auth/login&quot;, <br>      logout: &quot;auth/logout&quot;<br>    })<br>  },<br>  computed: {<br>    ...mapGetters({ loggedIn: &quot;auth/isLoggedIn&quot; })<br>  }</pre><p>So, the “<em>auth/login</em>” action is linked to the <em>login </em>method, the “<em>auth/logout</em>” to <em>logout </em>and the “<em>auth/isLoggedIn</em>” getter to the “<em>loggedIn</em>” computed property in a more readable way.</p><p>In this way we have a nice backbone to use for the next steps, in the next lesson we are going to finally create an input system to create posts and comments and push them into the store.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef364b572422" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social application with Vue.js and GO]]></title>
            <link>https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-3a11d506fc38?source=rss-90a990ce37dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a11d506fc38</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Ivano Dalmasso]]></dc:creator>
            <pubDate>Mon, 01 Mar 2021 10:09:20 GMT</pubDate>
            <atom:updated>2021-04-14T10:57:22.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*9RcvJALOdCOUBieIJCCMEg.jpeg" /><figcaption>Logo credits to vuejs.org and golang.org</figcaption></figure><h4>Create and serve a twitter like application with vue.js and golang PART 4: VUEX first setup</h4><p>This is the fourth part of this serie. Check here all the parts:</p><ul><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4e4db0cdde64">Part1: Setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64b3adee8dac">Part2: Getting started with VUE</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-24a1d1e7137d">Part3: Components &amp; slots</a></li><li>Part4: Vuex first setup(This)</li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-ef364b572422">Part5: VUEX finalization</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-a22a1afb76eb">Part6: Forms and data in Vuex</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-d9e563466b66">Part7: Connection with golang server</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64978f7c381f">Part8: Token-based authentication</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4d0caa37ddac">Part9: Store authentication token with indexedDB</a></li></ul><p>In this lesson we are going to add vuex, a centralized data store. This will give us the possibility to get and put data from there from all over the application.</p><p>Main target here is to update the frontend project, you can find the code <a href="https://github.com/idalmasso/go-vue-tutorial-frontend/releases/tag/v0.4">here</a>.</p><h4>What is vuex?</h4><p>Before actually start working, let’s explain a little about what is vuex and what it can do for our application.</p><p>Vuex is a state management library that centralizes some of the data of the application, so it can be accessed from any component.</p><p>This is really useful, because working only with props and events for passing data can be nice and easy for component-to-component transmission, but for any application with multiple layers of components this would become really complicated.</p><p>This complication can be solved using a centralized store, in this case, vuex.</p><p>In this lesson we are going to insert the posts list in this store, and we’ll see how to setup it in an easy and modular way.</p><p>The configuration of the vuex store is going to be in a dedicated “store” folder, that the vue cli has already added for you if you used vuex at the start of the project setup. If not,you can just install it with npm install and create the store folder.</p><p>Inside the folder there is an index.js file that contains the setup and configuration of the store. It should be something like this:</p><pre>import Vue from &#39;vue&#39;<br>import Vuex from &#39;vuex&#39;</pre><pre>Vue.use(Vuex);</pre><pre>export default new Vuex.Store({<br>  state: {  },<br>  mutations: {  },<br>  actions: {  },<br>  modules: {  }<br>});</pre><p>It instructs Vue on how to use vuex and then exports a new vuex store. It passes to the constructor a configuration object with the following parameters:</p><ol><li>state: the actual “data” inside of the vuex store (just imagine it as the “data” parameter of a component). The state is made reactive by vue, so each change to the data is also reflected to the components.</li><li>mutations: a list of synchronous functions that have to be called to change some data in the state. Each of this functions get the actual vuex state and a payload (it can be a custom object). A mutation is actually called passing its name to the “commit” method of the store.</li><li>actions: another list of functions. These have to actually call a mutation to change some data, but can be asynchronous. Actually, you should never call a mutation from a component, but always do it from actions, and call these last ones from the components. <br>An action gets in input a context object that contains the same set of methods/data of the store instance as first parameter, and can also get a custom object as second parm. An action is actually called passing the name as parameter in the “dispatch” method of the store.</li><li>getters: a list of functions that actually work as computed properties for a vuex store.</li><li>modules: a list of vuex modules. In bigger application the store can become really huge, so it is better to split the data and the code for different application scopes in different application modules. In this application we are going to use them also if it is not mandatory. A module itself is actually only a normal exported vuex configuration object. All modules share the same name space, so, for example, if a module use a state variable with name “name”, another module cannot. To solve this problem the modules can be “namespaced”, this actually means that all the names will have a named namespace prefix.</li></ol><h4>Add modules to the application</h4><p>Start by create two new folders in the store one called “postStore” and “userStore”. Each of them will contain a module, inside each create an “index.js” file. in the postStore add the following code:</p><pre>export default {<br>  namespaced: true,<br>  state: {<br>    posts: [<br>      {<br>        id: 1,<br>        user: &quot;idalmasso&quot;,<br>        date: &quot;2021-01-19 15:30:30&quot;,<br>        post:<br>          &quot;Today I&#39;m feeling sooooo well...&quot;,<br>        comments: [<br>          {<br>            id: 3,<br>            user: &quot;Nostradamus&quot;,<br>            date: &quot;2021-01-20 20:30:34&quot;,<br>            post: &quot;LOL&quot;<br>          },<br>          {<br>            id: 4,<br>            user: &quot;FinnishMan&quot;,<br>            date: &quot;2021-01-20 20:30:34&quot;,<br>            post: &quot;Please...&quot;<br>          }<br>        ]<br>      },<br>      {<br>        id: 2,<br>        user: &quot;cshannon&quot;,<br>        date: &quot;2021-01-19 15:25:20&quot;,<br>        post: &quot;Say something here&quot;<br>      }<br>    ]<br>  },<br><br>  mutations: {<br>    ADD_POST(state, post) {<br>      state.posts.push(post);<br>    },<br>    DELETE_POST(state, id) {<br>      state.posts = state.posts.filter(post =&gt; post.id != id);<br>    }<br>  },<br>  actions: {<br>    async addPost(context, post) {<br>      context.commit(&quot;ADD_POST&quot;, post);<br>    },<br>    async deletePost(context, id) {<br>      context.commit(&quot;DELETE_POST&quot;, id);<br>    }<br>  },<br>  getters: {<br>    allPosts(state) {<br>      return state.posts;<br>    },<br>    userPosts: state =&gt; user =&gt; {<br>      return state.posts.filter(post =&gt; post.user === user);<br>    }<br>  }<br>};</pre><p>Here we can see all the things we talked about before: the module is actually namespaced by the flag “namespaced”, there is a state containing the “posts” list, there are two mutations, ADD_POST and DELETE_POST that manipulate the state, the actions contains two async functions that commits the relative mutations, and finally there are two getters function to get all the posts and the list of the posts of a user.</p><p>This code is almost self-explanatory, so just add also the index.js in the UserStore folder like this:</p><pre>export default {<br>  namespaced: true,<br>  state: {<br>    user: {<br>      id: 1,<br>      username: &quot;idalmasso&quot;,<br>      description: &quot;Here is the description&quot;,<br>      //here there will be the logic for auth and so on...<br>      loggedIn: false<br>    }<br>  },<br>  mutations: {<br>    LOGIN(state) {<br>      state.user.loggedIn = true;<br>    },<br>    LOGOUT(state) {<br>      state.user.loggedIn = false;<br>    }<br>  },<br>  actions: {<br>    async login(context) {<br>      context.commit(&quot;LOGIN&quot;);<br>    },<br>    async logout(context) {<br>      context.commit(&quot;LOGOUT&quot;);<br>    }<br>  },<br>  getters: {<br>    currentUser(state) {<br>      return state.user;<br>    }<br>  }<br>};</pre><p>Here the state contains a user object, that contains the actual logged user, (that will be always the same, right by now… We’ll change that), and two mutations and actions to use for the login/logout functionality. Right by now, this only do the work in the vuex store, so it is not really useful, but this is almost only as a placeholder for future functionalities.</p><p>Now, to use the two modules we should only import and add them to the main index.js in the store folder in the right parameter:</p><pre>import postsModule from &quot;./postStore/index.js&quot;;<br>import usersModule from &quot;./userStore/index.js&quot;;<br>...<br> modules: { posts: postsModule, users: usersModule }<br>...</pre><p>Note that we have given the name “posts” to the postsModule and “users” to the usersModule. Because the two modules are namespaced, this name will be the prefix to use when referencing objects they contains.</p><p>Now last thing to do to see the actual posts in the components is to use them: just go in the Posts.vue component, and remove from the data configuration parameter the “<em>posts</em>” array and create a new computed method also named “<em>posts</em>” (so nothing else needs to be changed):</p><pre>computed: {<br>    posts() {<br>      return this.$store.getters[&quot;posts/allPosts&quot;];<br>    }<br>}</pre><p>So, here we can see that we can access the objects inside the store via the “$store” keyword in the vue instance. Note how the <em>allPosts</em> method name is prefixed with the module name.</p><p>Also, remove the posts list and the user in the User.vue component’s data parameter. Then, add the following two computed methods:</p><pre>userPosts() {<br>  return this.$store.getters[&quot;posts/userPosts&quot;](this.user.username); <br>},    <br>user() {<br>  return this.$store.getters[&quot;users/currentUser&quot;];    <br>}</pre><p>So, the userPosts get the parameter “this.user.username” that is gotten from the second computed method (remember that computed methods don’t have parenthesis when called).</p><p>Now, with this all set up, the posts and the users management is going to be centralized in the store (as well, in future, also for the authentication stuff). In next chapter we’re going to actually change a bit about this store and start make use of its functionality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a11d506fc38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social application with Vue.js and GO]]></title>
            <link>https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-24a1d1e7137d?source=rss-90a990ce37dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/24a1d1e7137d</guid>
            <category><![CDATA[vue-router]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Ivano Dalmasso]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 09:46:57 GMT</pubDate>
            <atom:updated>2021-05-28T14:56:48.928Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*9RcvJALOdCOUBieIJCCMEg.jpeg" /><figcaption>Logo credits to vuejs.org and golang.org</figcaption></figure><h4>Create and serve a twitter like application with vue.js and golang PART 3: COMPONENTS &amp; SLOTS</h4><p>This is the third part of this serie. Check here all the parts:</p><ul><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4e4db0cdde64">Part1: Setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64b3adee8dac">Part2: Getting started with VUE</a></li><li>Part3: Components &amp; slots (this)</li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-3a11d506fc38">Part4: Vuex first setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-ef364b572422">Part5: VUEX finalization</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-a22a1afb76eb">Part6: Forms and data in Vuex</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-d9e563466b66">Part7: Connection with golang server</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64978f7c381f">Part8: Token-based authentication</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4d0caa37ddac">Part9: Store authentication token with indexedDB</a></li></ul><p>In this lesson we are going to add some frontend functionalities, and by doing this we’ll learn a little more about using components and how to extend them with slots.</p><p>Main target here is to update the frontend project, you can find the code <a href="https://github.com/idalmasso/go-vue-tutorial-frontend/releases/tag/v0.3">here</a>.</p><h4>Reusing components for posts</h4><p>In the last lesson we created a list where we could see the posts of a user. Now, that view was not really nice, so here we are going to add css to make it a little better.</p><p>Additionally, we are going to create a card component that we’ll use again in other places in our application, so that the feeling that a user will have overall will be always the same.</p><p>Create a new component in the UI folder, and call it “BaseCard.vue”. Inside write the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0b3457eb9e5ed2680a6dea6f753c55b/href">https://medium.com/media/d0b3457eb9e5ed2680a6dea6f753c55b/href</a></iframe><p>The style tag is actually filled with the minimum code that lets the application have a better look, but of course this is for demonstrative purpouses.</p><p>Let’s explain briefly the scripts tag: there is one prop, actually, called “expandable” that will be passed from outside to this component. Note that this time the declaration of the prop is made in a different way: in fact the props parameter accept both an array or a javascript object, and in this second case we can pass the props as objects where we can describe better the kind of properties the prop should have.</p><p>In this example, we have set a type, Boolean, and a default value of false for the “expandable” prop.</p><p>The data property contains only a value that indicates if the card actually is or is not expanded, and we have a method “toggleDetails” that toggles the expansion of the card.</p><p>There is also another configuration option that we have never seen before: “computed”.</p><p>This is an object containing functions that can be actually used as data values. So we can use them (also in the template) as if they were data values (no parentheses needed), and they also have reactive behaviour.</p><p>In fact, vue internally knows if some dependency of a computed value is changed, and re-evaluate the computed method only when needed. In our code, the messageValue computed properties will automatically be re-evaluated only when “this.expanded” changes.</p><p>Note that in the methods and computed properties we can use any other data, method or computed property using the keyword “this”, as if we were in an object of a class.</p><p>Lastly, the template: here there are two new things added, v-if and the slots.</p><p>The v-if construct creates or deletes an element from the DOM depending on the validity of a condition. This have to be written exactly as with the v-for, so we can also insert a little logic here (but normally is always better create a computed property or a method to do this, so we can have more separation from code).</p><p>In our example, the header section is rendered only if there is a $slots.header variable set.</p><p>Last and more important point, is the use of slots. Actually, using a slot in a component let the developer to insert from the outside some content and then extends the internal component.</p><p>It works like this: everything that is inserted in the father template into the value of the component tag of the child, is actually inserted where the “slot” tag is in the child component. This is all you need to do in case of only one slot.</p><p>If you need to set more then one slot, like in the example above, you can insert “named slots” in the children, so slots have a name parameter.</p><p>In this last scenario, one slot can also be left without name, and this will be actually called “default slot”. In the father, in this case, the value to be replaced should be placed inside an additional tag “template” and a parameter “v-slot:slotName” where slotName is the name of the slot of the child.</p><p>Again in the example we need to insert in the father a “&lt;template v-slot:header&gt;” tag for inserting into the header slot.</p><p>Now in the file SinglePost.vue we can change the template to use this component BaseCard in the actual SinglePost template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2974f6337e58c58d1559e65646bee4fe/href">https://medium.com/media/2974f6337e58c58d1559e65646bee4fe/href</a></iframe><p>Here we used a card that can be expanded if there are some comments, so actually the post object is going to have an upgrade to also contain them.</p><p>In the header we can see the title of the post, and as a footer we inserted another list of cards that contains each a comment.</p><p>For semplicity of code we used the same structure for comment and post objects, so they can share some functions (like “postTitle”).</p><p>Next thing to do, go in the Posts.Vue component and change the “posts” variable to contain some comments in every post, i.e.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0bb23bc798ed59fd75403262a8f19bf/href">https://medium.com/media/b0bb23bc798ed59fd75403262a8f19bf/href</a></iframe><p>We did not import the BaseCard into our component: because we’ll propably reuse this “Base” component a lot inside of our app, we can import it inside the initial Vue object, in main.js, and then set it in the “components” configuration parameter of the Vue global instance.</p><h4>Changing the about page</h4><p>Just to complete a little more the app, also change the “About.vue” component in a User.vue, that will show the user actually logged in and his posts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca2d6d21914daabe93a72400ec43f84b/href">https://medium.com/media/ca2d6d21914daabe93a72400ec43f84b/href</a></iframe><p>This is actually self explainatory: the page is a simple one with a title consisting of the user’s username and shows a little description before displaying all of his posts. Actually the data is still some dummy block of objects, we’ll fix that later.</p><p>Setting a “title” parameter in the post-list, requires to also set that value in the props configuration parameters of the child component. Moreover, having removed the “About” component, we have to also update the index.js file inside the router to point to this new component.</p><p>At this point, it is mandatory a little explanation regarding the vue router: it is actually a component that lets you organize, maintain and correct the routing between different pages in your application. In a PWA the page is not loaded from the server each time, but this behaviour is actually simulated by the code, and this is what the router actually does.</p><p>First thing to do, is to check if in the main.js file the router is actually imported and registered in the vue application.</p><p>The router lets the application to have different pages, and show them only when called. Also it interacts with the browser “back” and “forward” buttons, so that this will seem to the user as if multiple pages are called and showed, while in reality only the routed piece of the page is changed by scripts.</p><p>As we seen before, the two foundamental tags that interact with the vue-router are &lt;router-link&gt; and &lt;router-view&gt;: the first is an actual link (it is actually a component that extends the &lt;a&gt; tag) and requires a “to” parameter, that can also be a javascript object, that points to the page to be shown. The other one is a placeholder that says to the router where is the point where the routed view should be injected.</p><p>Looking at the index.js file in the router folder we can see also the configuration of the router:</p><pre>Vue.use(VueRouter);</pre><p>This first line instruct Vue to use the VueRouter. Write at the end of the router file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e8b35c18cbb5a956aeaff34be01d87a/href">https://medium.com/media/0e8b35c18cbb5a956aeaff34be01d87a/href</a></iframe><p>Essentially it creates a VueRouter and export it, using as base url the base url of the application, using mode “history”, so it will use the history pushstate API to achieve url navigation (more <a href="https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations">HERE</a> ) and then pass at the constructor the list of the routes that it will have to use.</p><p>This list of routes is defined in the lines before this construct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63a0584f64ea2915e34feefbc3ef3388/href">https://medium.com/media/63a0584f64ea2915e34feefbc3ef3388/href</a></iframe><p>This is a list of objects that defines the actual routes that can be called from the router. In each object is set the path of the url (so, in the example, the root will be served by the first route, while the “/user” path by the second), a name, and the component that will be used to render the router view on that route.</p><p>The name is normally used in the router links to reference the route of the link decoupling it from the url (we have done it before, in the application bar, the router-links tag have a to parameter that points to an object with a name parameter set, remember?)</p><p>At last, we have the props configuration parameter, set to true in the last route: with that we instruct the vue-router that the router-links can pass some props to the component. This is important, because the default behaviour of the router is to not pass these props.</p><p>Having set this to true, in future we will be able to change the calls to the User page to have a different user.</p><p>With this we have done a little regression on vue router, if you now launch the frontend the application starts looking better, the data is still static and cannot be changed by the user, but we’ll be there in the next couple of lessons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24a1d1e7137d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social application with Vue.js and GO]]></title>
            <link>https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64b3adee8dac?source=rss-90a990ce37dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/64b3adee8dac</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Ivano Dalmasso]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 14:09:20 GMT</pubDate>
            <atom:updated>2021-05-28T08:18:45.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*9RcvJALOdCOUBieIJCCMEg.jpeg" /><figcaption>Logo credits to vuejs.org and golang.org</figcaption></figure><h4>Create and serve a twitter like application with vue.js and golang PART 2: GETTING STARTED WITH VUE</h4><p>This is the second part of this serie. Check here all the parts:</p><ul><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4e4db0cdde64">Part1: Setup</a></li><li>Part2: Getting started with VUE (this)</li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-24a1d1e7137d">Part3: Components &amp; slots</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-3a11d506fc38">Part4: Vuex first setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-ef364b572422">Part5: VUEX finalization</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-a22a1afb76eb">Part6: Forms and data in Vuex</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-d9e563466b66">Part7: Connection with golang server</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64978f7c381f">Part8: Token-based authentication</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4d0caa37ddac">Part9: Store authentication token with indexedDB</a></li></ul><p>In this lesson we are going to remove most of the code automatically created by the vue CLI, and add a little of our own.</p><p>Main target here is to update the frontend project, you can find the code <a href="https://github.com/idalmasso/go-vue-tutorial-frontend/releases/tag/v0.2">here</a>.</p><h4>The project structure</h4><p>Before going on with coding and stuff, let’s review the frontend project structure we are working with. If you followed the last story, or just downloaded the code that was in there, you should find yourself in the following situation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*aWvMGEcICLDaes3BtZRz9A.png" /><figcaption>Structure of folders</figcaption></figure><p>You should also find a node_modules folder, that actually contains the actual node modules that are installed with npm, and that work “behind the scenes” for us. If you got the code from my repo, just run</p><pre>npm run install</pre><p>to add that folder and the dependencies.</p><p>I want to point about the more important things here, so going by steps:</p><ul><li>the file package.json contains the configuration of the entire frontend project. Inside of it there is the name of the application we are building, a series of scripts to be used, and the dependencies that the project need to have installed to run. Also, there is a section relative to the dependencies that are used in development time to create the application.</li><li>the “public” folder: all its content will be copied in the build. Here we can find some icons (some default icons by vue, you can change them), a favicon, the robot.txt file and the index.html. This will be actually the real entry point of our application, opening it you can find an html file with some headers and only a single div, with a particular id, “app”. In build time in this file will be injected the scripts we’ll write into the other sections by a component called htmlWebpackPlugin that actually does it for us behind the scenes.</li><li>the “src” folder: contains all the javascript code, managed as we prefer, but there are some “best practices” we’re going to follow for this.</li></ul><h4>The application code of a vue project</h4><p>The “main.js” file is the one that “start” the vue application, creating a Vue instance, via the following code (I removed some parts that are not rilevant right by now)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e4723e0ab666c3e4fc5d9ece3e6568e/href">https://medium.com/media/2e4723e0ab666c3e4fc5d9ece3e6568e/href</a></iframe><blockquote>Note: if you are using Vue 3 this file could be a little different</blockquote><p>This code imports vue, and then from the file “./App.vue” it imports the “App” component. It then create a new Vue instance and pass it a configuration object with only a “render” parameter: this is a function that says the browser to load and render the actual “App” component. After the instance is created, it mounts it in the html in the node with id “app” (that is, as we seen before, in the index.html file).</p><p>In this way, all the content of the “app” node is actually “controlled” by the vue instance and it’s content derives from what we will write in the “App” component, that is, actually, in the App.vue file.</p><p>But what is a component?</p><p>A component is the foundamental building block of a vue application. It includes three principal parts: the html structure, some javascript code, and the css style used (in reality a better definition of a component can be found in the vue homepage, go and check it!).</p><p>An important feature of components, is that they can use other components inside them. In fact, the Vue instance is actually a big component, built over the app node, that uses inside other components.</p><p>In the project folder we build our application inside files with extension .vue, that will be compiled, build and put together at build time and they will be put inside the javascript code of the application. Note that in the completed build, like this, there will be no trace of *.vue files, but only the bundled *.js ones.</p><p>The “standard” structure of a .vue file is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/933a6fb124931061505348b0a35daa17/href">https://medium.com/media/933a6fb124931061505348b0a35daa17/href</a></iframe><p>We can see here three differents parts, divided by tags:</p><ol><li>the template, that contains the html of the page</li><li>the script, that contains the script that the component should work with (and this should include the export of a Vue configuration object)</li><li>the style, written with in css. Note, this will be shared among all the application, and normally this is not wanted, so usually the style tag has one more parameter “scoped”, that actually let the style to target only the actual component</li></ol><p>The vue files are actually create into the src folder anywhere one would like to, but normally a “best practise” is to have a “view” folder that contains components that are actually “whole page”, and a “components” folder that contains the more little pieces that are used inside the page.</p><h4>Begin working on our app</h4><p>After this little briefing, let’s start with writing some code and manipulate the project.</p><p>As first step, we’re going to delete most of the application we have already from the vue cli, and then update it with our code. I’d like to start having a page where a user can see a list of posts, with a top application bar where there are some menu items that will do some navigation between the pages.</p><p>Delete all files inside the “components” folder, and also the “Home.vue” file inside the view folder. What we are going to do is actually replacing it with a Posts component that will show all posts.</p><p>Next step, create the file “Posts.vue” in the view folder (this will be a page so we put it here) and here insert the structure we said before for a vue file. Thinking ahead, in other pages we will also want to put some list of maybe different, filtered posts… So we are going to use a component called “PostList” in it, that will be reusable in other pages too.</p><p>Create then also a file “PostList.vue” in the components folder (with the same logic as before) and, just to fully use the separation and reusability of the components, create also a SinglePost.vue component inside that folder, that will contain the code and the visual referred to a single post.</p><p>Let’s start filling the code in the Posts.vue component with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13d8760e12f8a823549f52902608af4e/href">https://medium.com/media/13d8760e12f8a823549f52902608af4e/href</a></iframe><p>The style tag is empty right by now, then we can omit it.</p><p>In this code we can see the first important configuration option: data. Data is a configuration function that has to return an object filled by the actual data that is going to be used in the component. In this case, I just put in this object an array ‘posts’ of post-like fake objects. In future this will be populated from a server, but right now this is perfectly fine.</p><p>Before of the data option, there is the “components” one. This is an object containing all the sub-components that are used inside this actual one. In this case, for example, we are going to use the “PostList” component. Of course, this cannot know where to go to search for this component, so we have to import it by</p><pre>import PostList from &quot;../components/PostList.vue&quot;;</pre><p>This is all there is to say about the code configuration options.</p><p>We are instructing vue with knowledge about some data, and also that we are going to be using somewhere one other component.</p><p>In the html template we can find the link with these two parameters: inside this we have set a root div with a class equal to “posts”, just to have a single root (actually, in vue 2 the template have to be single-rooted, this is no longer true in vue 3, so there you could also omit this), then set a title “Posts” and then a tag &lt;post-list&gt; with a strange parameter :post=”posts”.</p><p>This is actually the more important part for this page: post-list is actually the PostList component (vue actually can do this translation for you, for coherence with the html standard that is not camelcase), but then it comes the parameter. The : before the parameter name is actually a shorhand for “v-bind:” (so you could also write &lt;post-list v-bind:posts=”posts”&gt;) and that is a vue directive that link the actual value of the parameter with a value described in the script data option, in this case with the posts value. This creates a dynamic binding with the value, this means that if for any cause the value in the array should change, also the rendered value would do.</p><p>Next we are going to implement the PostList component, that will receive this posts and display them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7a24fe432c4aacb5ccf04bf3c9634ca/href">https://medium.com/media/a7a24fe432c4aacb5ccf04bf3c9634ca/href</a></iframe><p>The script part is actually really similar to before: it imports the SinglePost component and declare it in the configuration object.</p><p>The new option that we can see in this file is “props”: here we define all the values that can be passed to this actual component from other “father” components as parameters. So in this case, we say that if any component uses “PostList”, it can set a parameter called “posts”.</p><p>In the template section there is the tag “single-post”, that will be the component that shows a single post. Inside this tag, there is a new construct of vue, that actually cycle between groups of data, the “v-for” construct. The syntax of the v-for is actually really simple: v-for=”element in listOfElements” : vue will dynamically and automatically multiply this tag for each element in the listOfELements, or, in our case, for each post in the posts array.</p><p>The second parameter we can see is :key (again, the : is for v-bind). This is actually a parameter of the v-for, that lets vue to identify what is actually the data that can change inside each instance of the cycle.</p><p>The :post ending parameter is for the actual SinglePost that will get it as a prop. Note that this last parameter takes the output value of the v-for loop, with a name that is actually the one created there.</p><p>Finally, note that we can use the v-bind directive on a prop just as we used it with the data option before.</p><p>Finally, we can write the SinglePost code like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccc96ec1defb8020a1b3809e0ac861d2/href">https://medium.com/media/ccc96ec1defb8020a1b3809e0ac861d2/href</a></iframe><p>This is not going to use any other component right by now, so no import statements here.</p><p>There is only the definition of the “post” prop, and then we have another new configuration option: methods is actually an object that contains a serie of javascripts methods that can be called, here we have set a method “postTitle” that receive a post and returns a representative title about it.</p><p>In the template we can see how we can render in the html the value of the data we have in our component: we can use the {{ value }} syntax, where “value” is actually a javascript string object that will be rendered. We can also pass methods here, as postTitle(post), and at render time this will be called (and will also be called, and so can change, anytime anything is changed in the component values).</p><p>Actually if you have already worked with vue you’ll wonder why I’m not using a computed property here, that is because after I’ll use this method also for the comments title, and didn’t want to create a “comment” component, so this will be ok.</p><p>With all of this settled, we have to change a little the router.js file to make sure that the application is pointing to our pages. We haven’t talked about router until now, we’ll do in some next lesson, so for now just copy the following code in it (we actually just replaced the Home vue CLI created component with our new Posts one):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d79f1c8f51a41c3f2acd0d24984cc2ef/href">https://medium.com/media/d79f1c8f51a41c3f2acd0d24984cc2ef/href</a></iframe><p>And finally, we create the vue component for the application bar that will do the navigation. In ‘./components’ create a new folder “UI” and there add a file “TheApplicationBar.vue”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d9e997b4e82a1f6085e098f92cdab6f/href">https://medium.com/media/2d9e997b4e82a1f6085e098f92cdab6f/href</a></iframe><p>Here I just added a little of css style so the application bar can stay on top and remains over everything. Note that the scoped parameter lets this style to be only used for this component.</p><p>Regardint the code: the data option returns a list of “link” object that can be reached and that have to stay in the application bar. These objects contains a name (that is displayed by the application bar) and a “to” parameter, that actually contains the name of the router page where we want to route (more about this in one of the next lessons).</p><p>In the template there is only this “router-link” new tag, that is actually a link that routes the navigation using the router to the page named by the “to” parameter.</p><p>We want this “to” to be dynamically selected by the data option in the scripts, so we use the v-bind here, too.</p><p>We also added a “LOGIN” button, but for now this is not going to do anything.</p><p>Last thing to do for this application is to glue everything together, by putting this application bar inside the App.vue file, and removing anything else inside it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f5f218ce166cda02a7818e7a0bb27d6/href">https://medium.com/media/9f5f218ce166cda02a7818e7a0bb27d6/href</a></iframe><p>This should be clear by now, the style here is actually not scoped, so it will be used in all the application, and center everything a little bit.</p><p>This page uses only the application bar component, the only new thing is the “router-view” tag: this actually just shows the actual router selected view, so i.e. if one click in the application bar for the posts link, the router select that view and here it will be shown.</p><p>After this, you can actually test the application by running</p><pre>npm run serve</pre><p>and opening the browser at <a href="http://localhost:8080/">http://localhost:8080</a>.</p><p>In the next lessons we’re going to add some other functionalities at the frontend only application, and learn a little more about vue. After we’ll have a little functioning frontend, we’ll go to the backend, to store and retrieve all the data from it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64b3adee8dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social application with Vue.js and GO]]></title>
            <link>https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4e4db0cdde64?source=rss-90a990ce37dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e4db0cdde64</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Ivano Dalmasso]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 14:32:38 GMT</pubDate>
            <atom:updated>2021-05-28T08:05:01.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*9RcvJALOdCOUBieIJCCMEg.jpeg" /><figcaption>Logo credits to vuejs.org and golang.org</figcaption></figure><h4>Create and serve a twitter like application with vue.js and golang PART 1: SETUP</h4><p>In this serie of articles I want to write down a little tutorial about using vue.js as frontend and go as backend as a choice for a website/web application. This couple seems not to be very popular, but let’s think about this: Go is actually a very fast backend language, built by google to be both fast and easy to use and Vue is a javascript framework that takes the fast rendering of a page a point of main importance.</p><p>Said this I think that using them together is gonna be really nice, and let us create applications that could be very good performance wise.</p><p>Check out the other parts:</p><ul><li>Part1: Setup (this)</li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64b3adee8dac">Part2: Getting started with VUE</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-24a1d1e7137d">Part3: Components &amp; slots</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-3a11d506fc38">Part4: Vuex first setup</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-ef364b572422">Part5: VUEX finalization</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-a22a1afb76eb">Part6: Forms and data in Vuex</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-d9e563466b66">Part7: Connection with golang server</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-64978f7c381f">Part8: Token-based authentication</a></li><li><a href="https://ivano-dalmasso.medium.com/social-application-with-vue-js-and-go-4d0caa37ddac">Part9: Store authentication token with indexedDB</a></li></ul><h4>What are we going to build</h4><p>In this tutorial we are going to create a little social web application that lets users authenticate, create some text posts, and comment to posts made by other persons.</p><p>I’ll try not to go in great depth for the majority of the course, but take only the essential things that can make a person “ready to go” with a project.</p><p>The code for this first part can be found in:</p><p><a href="https://github.com/idalmasso/go-vue-tutorial-backend/releases/tag/v0.1">Backend</a></p><p><a href="https://github.com/idalmasso/go-vue-tutorial-frontend/releases/tag/v0.1">Frontend</a></p><p>In this first chapter we are going to set up our project and make things nice and ready to go for the following parts.</p><h4>Setting up</h4><p>Let’s create a folder in the code repository, that will contain all our code. I’ll call from here on this folder the “primary folder”.</p><p>Here add the two repositories for the projects (i.e. create them on github and clone them) and then we will be ready to setup the two projects. I will call “frontend folder” and “backend folder” the two folders that contain the two repositories from now on.</p><p>First point, we go for the frontend part; I expect to have already npm installed (if not, go and install it from <a href="https://www.npmjs.com/get-npm">https://www.npmjs.com/get-npm</a>).</p><p>We need to have the vue-cli installed, just calling</p><pre>npm install -g @vue/cli</pre><p>This will install globally the command line interface of vue. After the command is completed, we can finally initialize the vue project using</p><pre>vue create &quot;frontend folder&quot;</pre><p>where obviously “frontend folder” is the name you have given to your frontend repo folder (so it will create the project inside of that folder).</p><p>The CLI will ask then for a series of options, in the first selection just select “Manually select features”, and in the second selection make sure to select “Choose Vue version”, “Babel”, “Progressive Web App (PWA) Support”, “Router”, “Vuex”, “Linter/Formatter”.</p><p>The options we have selected will be explained more in details in other chapters, just know that PWA is the support for making the site a Progressive Web Application (<a href="https://en.wikipedia.org/wiki/Progressive_web_application">https://en.wikipedia.org/wiki/Progressive_web_application</a>), the router will get us routing capabilities inside of our frontend application, and vuex will give us a centralized store.</p><p>In the next selection it will asks for the vue version. I made this tutorial with vue 2, but feel free to select a different selections, the changes aren’t that big and almost everything will work in both versions for this project.</p><p>Leave all the following selection as the default (if you prefer some better linter configs, feel free to use what you prefer).</p><p>The installer then automatically will go and create all the project structure inside that folder for you. When it has finished, enter the folder and launch</p><pre>npm run serve </pre><p>this will create a little development server, and you can now go in your browser @ <a href="http://localhost:8080/">http://localhost:</a>8080/ and see the pages and the little base application that is created by the vue command line interface. Just stop the server by now, and let’s prepare the backend project too.</p><p>I assume that you have go installed, else go <a href="https://golang.org/dl/">here</a> and install it.</p><p>In the bakend folder, we’ll create a go module with the following command</p><pre>go mod init github.com/idalmasso/go-vue-tutorial-backend</pre><p>Obiously use the module name correct referred to your setup;</p><p>This will initialize your module and make it ready to be used.</p><p>Note: in previous version of GO you had to write all your code GOPATH, now with the modules you can do something like this, and put your code anywhere in your system</p><h4>The current situation</h4><p>Let’s take a moment and see what we have got in these two projects now.</p><p>In the backend folder there is a single file go.mod that contains the definition of the module, and will also contain all the packages needed.</p><p>In the frontend folder there are instead a lot more things:</p><ul><li>A node_modules folder, that contains all node modules that the vue cli has installed</li><li>A public folder, this contains a set of static assets that will be copied inside of the distribution folder when building the frontend</li><li>A src folder, that contains all javascript code that will be used for the vue frontend</li><li>Some other configuration files, in particular see the package.json that contains the configuration of the app and its dependencies. Inside this folder we can also set some utility scripts, in the “scripts” section, and there you can see the “serve” that we called before to create the development server. The “build” command, in particular, will build the complete Vue application and create a distribution folder, that has to be served by a real server of your preference.</li></ul><h4>A little improvement to the project setup</h4><p>Now, a real world project cannot be set on a development server, so the backend server we’ll build in golang will also be responsible to serve the vue application.</p><p>Wanting to decouple backend and frontend as much as possible, the best solution I have found is to create a git submodule in the backend project that points to a branch of the frontend project containing only the distribution project.</p><p>This is easier done then said: all we have to do is go in the frontend folder, and for first thing create a build of the actual application calling</p><pre>npm run build</pre><p>This will create the “dist” distribution folder, where there are all the files that need to be served for the frontend application to work. Next step is to push this as a different branch to github, for semplicity I have used an addon “push-dir”, that actually lets you push the content of a single directory. To do so, install the addon</p><pre>npm i -D push-dir</pre><p>and add a script inside of package.json like this:</p><pre>&quot;deploy&quot;: &quot;push-dir --dir=dist --branch=production --cleanup&quot;</pre><p>Calling then the command</p><pre>npm run deploy</pre><p>will actually do all the work for us.</p><p>Now, in the backend folder, we can create the submodule like this</p><pre>git submodule add -b production <a href="https://your_frontend_repository/">https://your_frontend_repository</a> dist</pre><p>We can now initialize the submodule with</p><pre>git submodule update --init</pre><p>and then update it with</p><pre>git submodule update --remote</pre><p>For easiness of use we can also add a package.json file in the backend folder with these two commands as scripts.</p><h4>Test the actual setup</h4><p>Last step is testing the setup we have just built: only thing needed is to create a little go backend that will be able to serve the dist folder.</p><p>If everything will work, we will be ready to start writing the real application.</p><p>Create a file in the backend folder, and name it “server.go”. Then add the following code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C184%252C195%252C0%2529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpackage%252520main%252520%25250Aimport%252520%2528%252520%25250A%252520%252520%252522fmt%252522%252520%25250A%252520%252520%252522log%252522%252520%25250A%252520%252520%252522net%25252Fhttp%252522%252520%252520%25250A%252520%252520%252522github.com%25252Fgorilla%25252Fmux%252522%25250A%2529%252520%25250Afunc%252520main%2528%2529%25257B%252520%25250A%252520%252520r%252520%25253A%25253D%252520mux.NewRouter%2528%2529%252520%25250A%252520%252520fs%252520%25253A%25253D%252520http.FileServer%2528http.Dir%2528%252522.%25252Fdist%252522%2529%2529%25250A%252520%252520r.PathPrefix%2528%252522%25252F%252522%2529.Handler%2528fs%2529%252520%25250A%252520%252520http.Handle%2528%252522%25252F%252522%25252Cr%2529%252520%25250A%252520%252520fmt.Println%2528%252522Listening%252522%2529%252520%252520%25250A%252520%252520log.Panic%2528%252520%252520http.ListenAndServe%2528%252522%25253A3000%252522%25252C%252520nil%2529%25252C%252520%25250A%252520%252520%2529%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C184%25252C195%25252C0%252529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpackage%25252520main%25252520%2525250Aimport%25252520%252528%25252520%2525250A%25252520%25252520%25252522fmt%25252522%25252520%2525250A%25252520%25252520%25252522log%25252522%25252520%2525250A%25252520%25252520%25252522net%2525252Fhttp%25252522%25252520%25252520%2525250A%25252520%25252520%25252522github.com%2525252Fgorilla%2525252Fmux%25252522%2525250A%252529%25252520%2525250Afunc%25252520main%252528%252529%2525257B%25252520%2525250A%25252520%25252520r%25252520%2525253A%2525253D%25252520mux.NewRouter%252528%252529%25252520%2525250A%25252520%25252520fs%25252520%2525253A%2525253D%25252520http.FileServer%252528http.Dir%252528%25252522.%2525252Fdist%25252522%252529%252529%2525250A%25252520%25252520r.PathPrefix%252528%25252522%2525252F%25252522%252529.Handler%252528fs%252529%25252520%2525250A%25252520%25252520http.Handle%252528%25252522%2525252F%25252522%2525252Cr%252529%25252520%2525250A%25252520%25252520fmt.Println%252528%25252522Listening%25252522%252529%25252520%25252520%2525250A%25252520%25252520log.Panic%252528%25252520%25252520http.ListenAndServe%252528%25252522%2525253A3000%25252522%2525252C%25252520nil%252529%2525252C%25252520%2525250A%25252520%25252520%252529%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6a6ffde0f8f60a96a97e2d737cbccd8/href">https://medium.com/media/a6a6ffde0f8f60a96a97e2d737cbccd8/href</a></iframe><p>This is actually a very basic code, starting with the package definition (main package, is the default for a starting point in a go application), followed by the imports, and then the main function, the starting point.</p><p>There the program creates a new gorilla router/http multiplexer.</p><p>With this object we can actually tell the server which endpoints should listen and also what it should respond. In this case, we create an http fileserver (called “fs”) that will serve the “./dist” folder (that is actually the frontend application, from the git submodule).</p><p>The following line say at the router that requests coming at “/” will be handled with the file server. The last call at http.ListenAndServe is a blocking one that creates the server at localhost:3000.</p><p>Now we can run the application, for example calling</p><pre>go run server.go</pre><p>and navigate with our browser at <a href="http://localhost:3000.">http://localhost:3000.</a></p><p>We can now see that our frontend application is there, served with our golang server.</p><h4>Is this necessary?</h4><p>This setup could seem a little complex: we could have just created and updated the application frontend, and when needed just builded and copied the folder.</p><p>In real world scenario probably the backend and frontend developers are different entities, so by doing this way both of them are indipendents and also this is a cleaner way to do the job.</p><h4>Next steps</h4><p>In the following chapters, we will start creating and updating our vue application to be of some real use.</p><p>After having some frontend created, we will try to add some backend functionality, so the frontend data will be get and/or sent to some api of the go server, and we will get some little levels of comunication and persistence.</p><p>We will then use a mongodb database to save the data, add a primitive version of authentication, and at the end we’ll work to make our application a PWA, so it will also work offline and could be installable on the device of the user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e4db0cdde64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>