自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

構(gòu)建一個(gè)即時(shí)消息應(yīng)用(七):Access頁(yè)面

開(kāi)發(fā)
這是一系列關(guān)于構(gòu)建“即時(shí)消息”應(yīng)用的新帖子。現(xiàn)在我們已經(jīng)完成了后端,讓我們轉(zhuǎn)到前端。 我將采用單頁(yè)應(yīng)用程序方案。

[[345596]]

本文是該系列的第七篇。

現(xiàn)在我們已經(jīng)完成了后端,讓我們轉(zhuǎn)到前端。 我將采用單頁(yè)應(yīng)用程序方案。

首先,我們創(chuàng)建一個(gè) static/index.html 文件,內(nèi)容如下。

  1. <!DOCTYPE html> 
  2. <html lang="en"
  3. <head> 
  4.     <meta charset="utf-8"
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0"
  6.     <title>Messenger</title> 
  7.     <link rel="shortcut icon" href="data:,"
  8.     <link rel="stylesheet" href="/styles.css"
  9.     <script src="/main.js" type="module"></script> 
  10. </head> 
  11. <body></body> 
  12. </html> 

這個(gè) HTML 文件必須為每個(gè) URL 提供服務(wù),并且使用 JavaScript 負(fù)責(zé)呈現(xiàn)正確的頁(yè)面。

因此,讓我們將注意力轉(zhuǎn)到 main.go 片刻,然后在 main() 函數(shù)中添加以下路由:

  1. router.Handle("GET""/...", http.FileServer(SPAFileSystem{http.Dir("static")})) 
  2.  
  3. type SPAFileSystem struct { 
  4.     fs http.FileSystem 
  5.  
  6. func (spa SPAFileSystem) Open(name string) (http.File, error) { 
  7.     f, err := spa.fs.Open(name
  8.     if err != nil { 
  9.         return spa.fs.Open("index.html"
  10.     } 
  11.     return f, nil 

我們使用一個(gè)自定義的文件系統(tǒng),因此它不是為未知的 URL 返回 404 Not Found,而是轉(zhuǎn)到 index.html。

路由器

在 index.html 中我們加載了兩個(gè)文件:styles.css 和 main.js。我把樣式留給你自由發(fā)揮。

讓我們移動(dòng)到 main.js。 創(chuàng)建一個(gè)包含以下內(nèi)容的 static/main.js 文件:

  1. import { guard } from './auth.js' 
  2. import Router from './router.js' 
  3.  
  4. let currentPage 
  5. const disconnect = new CustomEvent('disconnect'
  6. const router = new Router() 
  7.  
  8. router.handle('/', guard(view('home'), view('access'))) 
  9. router.handle('/callback'view('callback')) 
  10. router.handle(/^\/conversations\/([^\/]+)$/, guard(view('conversation'), view('access'))) 
  11. router.handle(/^\//, view('not-found')) 
  12.  
  13. router.install(async result => { 
  14.     document.body.innerHTML = '' 
  15.     if (currentPage instanceof Node) { 
  16.         currentPage.dispatchEvent(disconnect) 
  17.     } 
  18.     currentPage = await result 
  19.     if (currentPage instanceof Node) { 
  20.         document.body.appendChild(currentPage) 
  21.     } 
  22. }) 
  23.  
  24. function view(pageName) { 
  25.     return (...args) => import(`/pages/${pageName}-page.js`) 
  26.         .then(m => m.default(...args)) 

如果你是這個(gè)博客的關(guān)注者,你已經(jīng)知道它是如何工作的了。 該路由器就是在 這里 顯示的那個(gè)。 只需從 @nicolasparada/router 下載并保存到 static/router.js 即可。

我們注冊(cè)了四條路由。 在根路由 / 處,我們展示 home 或 access 頁(yè)面,無(wú)論用戶(hù)是否通過(guò)身份驗(yàn)證。 在 /callback 中,我們展示 callback 頁(yè)面。 在 /conversations/{conversationID} 上,我們展示對(duì)話(huà)或 access 頁(yè)面,無(wú)論用戶(hù)是否通過(guò)驗(yàn)證,對(duì)于其他 URL,我們展示一個(gè) not-found 頁(yè)面。

我們告訴路由器將結(jié)果渲染為文檔主體,并在離開(kāi)之前向每個(gè)頁(yè)面調(diào)度一個(gè) disconnect 事件。

我們將每個(gè)頁(yè)面放在不同的文件中,并使用新的動(dòng)態(tài) import() 函數(shù)導(dǎo)入它們。

身份驗(yàn)證

guard() 是一個(gè)函數(shù),給它兩個(gè)函數(shù)作為參數(shù),如果用戶(hù)通過(guò)了身份驗(yàn)證,則執(zhí)行第一個(gè)函數(shù),否則執(zhí)行第二個(gè)。它來(lái)自 auth.js,所以我們創(chuàng)建一個(gè)包含以下內(nèi)容的 static/auth.js 文件:

  1. export function isAuthenticated() { 
  2.     const token = localStorage.getItem('token'
  3.     const expiresAtItem = localStorage.getItem('expires_at'
  4.     if (token === null || expiresAtItem === null) { 
  5.         return false 
  6.     } 
  7.  
  8.     const expiresAt = new Date(expiresAtItem) 
  9.     if (isNaN(expiresAt.valueOf()) || expiresAt <= new Date()) { 
  10.         return false 
  11.     } 
  12.  
  13.     return true 
  14.  
  15. export function guard(fn1, fn2) { 
  16.     return (...args) => isAuthenticated() 
  17.         ? fn1(...args) 
  18.         : fn2(...args) 
  19.  
  20. export function getAuthUser() { 
  21.     if (!isAuthenticated()) { 
  22.         return null 
  23.     } 
  24.  
  25.     const authUser = localStorage.getItem('auth_user'
  26.     if (authUser === null) { 
  27.         return null 
  28.     } 
  29.  
  30.     try { 
  31.         return JSON.parse(authUser) 
  32.     } catch (_) { 
  33.         return null 
  34.     } 

isAuthenticated() 檢查 localStorage 中的 token 和 expires_at,以判斷用戶(hù)是否已通過(guò)身份驗(yàn)證。getAuthUser() 從 localStorage 中獲取經(jīng)過(guò)身份驗(yàn)證的用戶(hù)。

當(dāng)我們登錄時(shí),我們會(huì)將所有的數(shù)據(jù)保存到 localStorage,這樣才有意義。

Access 頁(yè)面

 

access page screenshot

讓我們從 access 頁(yè)面開(kāi)始。 創(chuàng)建一個(gè)包含以下內(nèi)容的文件 static/pages/access-page.js

  1. const template = document.createElement('template'
  2. template.innerHTML = ` 
  3.     <h1>Messenger</h1> 
  4.     <a href="/api/oauth/github" onclick="event.stopPropagation()">Access with GitHub</a> 
  5.  
  6. export default function accessPage() { 
  7.     return template.content 

因?yàn)槁酚善鲿?huì)攔截所有鏈接點(diǎn)擊來(lái)進(jìn)行導(dǎo)航,所以我們必須特別阻止此鏈接的事件傳播。

單擊該鏈接會(huì)將我們重定向到后端,然后重定向到 GitHub,再重定向到后端,然后再次重定向到前端; 到 callback 頁(yè)面。

Callback 頁(yè)面

創(chuàng)建包括以下內(nèi)容的 static/pages/callback-page.js 文件:

  1. import http from '../http.js' 
  2. import { navigate } from '../router.js' 
  3.  
  4. export default async function callbackPage() { 
  5.     const url = new URL(location.toString()) 
  6.     const token = url.searchParams.get('token'
  7.     const expiresAt = url.searchParams.get('expires_at'
  8.  
  9.     try { 
  10.         if (token === null || expiresAt === null) { 
  11.             throw new Error('Invalid URL'
  12.         } 
  13.  
  14.         const authUser = await getAuthUser(token) 
  15.  
  16.         localStorage.setItem('auth_user', JSON.stringify(authUser)) 
  17.         localStorage.setItem('token', token) 
  18.         localStorage.setItem('expires_at', expiresAt) 
  19.     } catch (err) { 
  20.         alert(err.message) 
  21.     } finally { 
  22.         navigate('/'true
  23.     } 
  24.  
  25. function getAuthUser(token) { 
  26.     return http.get('/api/auth_user', { authorization: `Bearer ${token}` }) 

callback 頁(yè)面不呈現(xiàn)任何內(nèi)容。這是一個(gè)異步函數(shù),它使用 URL 查詢(xún)字符串中的 token 向 /api/auth_user 發(fā)出 GET 請(qǐng)求,并將所有數(shù)據(jù)保存到 localStorage。 然后重定向到 /。

HTTP

這里是一個(gè) HTTP 模塊。 創(chuàng)建一個(gè)包含以下內(nèi)容的 static/http.js 文件:

  1. import { isAuthenticated } from './auth.js' 
  2.  
  3. async function handleResponse(res) { 
  4.     const body = await res.clone().json().catch(() => res.text()) 
  5.  
  6.     if (res.status === 401) { 
  7.         localStorage.removeItem('auth_user'
  8.         localStorage.removeItem('token'
  9.         localStorage.removeItem('expires_at'
  10.     } 
  11.  
  12.     if (!res.ok) { 
  13.         const message = typeof body === 'object' && body !== null && 'message' in body 
  14.             ? body.message 
  15.             : typeof body === 'string' && body !== '' 
  16.                 ? body 
  17.                 : res.statusText 
  18.         throw Object.assign(new Error(message), { 
  19.             url: res.url, 
  20.             statusCode: res.status, 
  21.             statusText: res.statusText, 
  22.             headers: res.headers, 
  23.             body, 
  24.         }) 
  25.     } 
  26.  
  27.     return body 
  28.  
  29. function getAuthHeader() { 
  30.     return isAuthenticated() 
  31.         ? { authorization: `Bearer ${localStorage.getItem('token')}` } 
  32.         : {} 
  33.  
  34. export default { 
  35.     get(url, headers) { 
  36.         return fetch(url, { 
  37.             headers: Object.assign(getAuthHeader(), headers), 
  38.         }).then(handleResponse) 
  39.     }, 
  40.  
  41.     post(url, body, headers) { 
  42.         const init = { 
  43.             method: 'POST'
  44.             headers: getAuthHeader(), 
  45.         } 
  46.         if (typeof body === 'object' && body !== null) { 
  47.             init.body = JSON.stringify(body) 
  48.             init.headers['content-type'] = 'application/json; charset=utf-8' 
  49.         } 
  50.         Object.assign(init.headers, headers) 
  51.         return fetch(url, init).then(handleResponse) 
  52.     }, 
  53.  
  54.     subscribe(url, callback) { 
  55.         const urlWithToken = new URL(url, location.origin) 
  56.         if (isAuthenticated()) { 
  57.             urlWithToken.searchParams.set('token', localStorage.getItem('token')) 
  58.         } 
  59.         const eventSource = new EventSource(urlWithToken.toString()) 
  60.         eventSource.onmessage = ev => { 
  61.             let data 
  62.             try { 
  63.                 data = JSON.parse(ev.data) 
  64.             } catch (err) { 
  65.                 console.error('could not parse message data as JSON:', err) 
  66.                 return 
  67.             } 
  68.             callback(data) 
  69.         } 
  70.         const unsubscribe = () => { 
  71.             eventSource.close() 
  72.         } 
  73.         return unsubscribe 
  74.     }, 

這個(gè)模塊是 fetch 和 EventSource API 的包裝器。最重要的部分是它將 JSON web 令牌添加到請(qǐng)求中。

Home 頁(yè)面

 

home page screenshot

因此,當(dāng)用戶(hù)登錄時(shí),將顯示 home 頁(yè)。 創(chuàng)建一個(gè)具有以下內(nèi)容的 static/pages/home-page.js 文件:

  1. import { getAuthUser } from '../auth.js' 
  2. import { avatar } from '../shared.js' 
  3.  
  4. export default function homePage() { 
  5.     const authUser = getAuthUser() 
  6.     const template = document.createElement('template'
  7.     template.innerHTML = ` 
  8.         <div> 
  9.             <div> 
  10.                 ${avatar(authUser)} 
  11.                 <span>${authUser.username}</span> 
  12.             </div> 
  13.             <button id="logout-button">Logout</button> 
  14.         </div> 
  15.         <!-- conversation form here --> 
  16.         <!-- conversation list here --> 
  17.     ` 
  18.     const page = template.content 
  19.     page.getElementById('logout-button').onclick = onLogoutClick 
  20.     return page 
  21.  
  22. function onLogoutClick() { 
  23.     localStorage.clear() 
  24.     location.reload() 

對(duì)于這篇文章,這是我們?cè)?nbsp;home 頁(yè)上呈現(xiàn)的唯一內(nèi)容。我們顯示當(dāng)前經(jīng)過(guò)身份驗(yàn)證的用戶(hù)和注銷(xiāo)按鈕。

當(dāng)用戶(hù)單擊注銷(xiāo)時(shí),我們清除 localStorage 中的所有內(nèi)容并重新加載頁(yè)面。

Avatar

那個(gè) avatar() 函數(shù)用于顯示用戶(hù)的頭像。 由于已在多個(gè)地方使用,因此我將它移到 shared.js 文件中。 創(chuàng)建具有以下內(nèi)容的文件 static/shared.js

  1. export function avatar(user) { 
  2.     return user.avatarUrl === null 
  3.         ? `<figure class="avatar" data-initial="${user.username[0]}"></figure>` 
  4.         : `<img class="avatar" src="${user.avatarUrl}" alt="${user.username}'s avatar">` 

如果頭像網(wǎng)址為 null,我們將使用用戶(hù)的姓名首字母作為初始頭像。

你可以使用 attr() 函數(shù)顯示帶有少量 CSS 樣式的首字母。

  1. .avatar[data-initial]::after { 
  2.     content: attr(data-initial); 

僅開(kāi)發(fā)使用的登錄

 

access page with login form screenshot

在上一篇文章中,我們?yōu)榫帉?xiě)了一個(gè)登錄代碼。讓我們?cè)?nbsp;access 頁(yè)面中為此添加一個(gè)表單。 進(jìn)入 static/ages/access-page.js,稍微修改一下。

  1. import http from '../http.js' 
  2.  
  3. const template = document.createElement('template'
  4. template.innerHTML = ` 
  5.     <h1>Messenger</h1> 
  6.     <form id="login-form"
  7.         <input type="text" placeholder="Username" required> 
  8.         <button>Login</button> 
  9.     </form> 
  10.     <a href="/api/oauth/github" onclick="event.stopPropagation()">Access with GitHub</a> 
  11.  
  12. export default function accessPage() { 
  13.     const page = template.content.cloneNode(true
  14.     page.getElementById('login-form').onsubmit = onLoginSubmit 
  15.     return page 
  16.  
  17. async function onLoginSubmit(ev) { 
  18.     ev.preventDefault() 
  19.  
  20.     const form = ev.currentTarget 
  21.     const input = form.querySelector('input'
  22.     const submitButton = form.querySelector('button'
  23.  
  24.     input.disabled = true 
  25.     submitButton.disabled = true 
  26.  
  27.     try { 
  28.         const payload = await login(input.value) 
  29.         input.value = '' 
  30.  
  31.         localStorage.setItem('auth_user', JSON.stringify(payload.authUser)) 
  32.         localStorage.setItem('token', payload.token) 
  33.         localStorage.setItem('expires_at', payload.expiresAt) 
  34.  
  35.         location.reload() 
  36.     } catch (err) { 
  37.         alert(err.message) 
  38.         setTimeout(() => { 
  39.             input.focus() 
  40.         }, 0) 
  41.     } finally { 
  42.         input.disabled = false 
  43.         submitButton.disabled = false 
  44.     } 
  45.  
  46. function login(username) { 
  47.     return http.post('/api/login', { username }) 

我添加了一個(gè)登錄表單。當(dāng)用戶(hù)提交表單時(shí)。它使用用戶(hù)名對(duì) /api/login 進(jìn)行 POST 請(qǐng)求。將所有數(shù)據(jù)保存到 localStorage 并重新加載頁(yè)面。

記住在前端完成后刪除此表單。


這就是這篇文章的全部?jī)?nèi)容。在下一篇文章中,我們將繼續(xù)使用主頁(yè)添加一個(gè)表單來(lái)開(kāi)始對(duì)話(huà),并顯示包含最新對(duì)話(huà)的列表。

 

責(zé)任編輯:龐桂玉 來(lái)源: Linux中國(guó)
相關(guān)推薦

2020-10-19 16:20:38

即時(shí)消息Conversatio編程語(yǔ)言

2020-10-16 14:40:20

即時(shí)消息Home頁(yè)面編程語(yǔ)言

2020-10-09 12:45:19

創(chuàng)建消息即時(shí)消息編程語(yǔ)言

2019-09-29 15:25:13

CockroachDBGoJavaScript

2020-10-09 15:00:56

實(shí)時(shí)消息編程語(yǔ)言

2019-10-28 20:12:40

OAuthGuard中間件編程語(yǔ)言

2020-03-31 12:21:20

JSON即時(shí)消息編程語(yǔ)言

2020-10-10 20:51:10

即時(shí)消息編程語(yǔ)言

2021-03-25 08:29:33

SpringBootWebSocket即時(shí)消息

2023-08-14 08:01:12

websocket8g用戶(hù)

2015-03-18 15:37:19

社交APP場(chǎng)景

2021-04-03 12:31:48

Python開(kāi)發(fā)數(shù)據(jù)科學(xué)

2014-10-15 11:01:02

Web應(yīng)用測(cè)試應(yīng)用

2018-08-22 17:32:45

2022-02-10 07:03:32

流量應(yīng)用架構(gòu)數(shù)據(jù)交換

2021-07-14 17:39:46

ReactRails API前端組件

2023-09-21 08:00:00

ChatGPT編程工具

2021-12-03 00:02:01

通訊工具即時(shí)

2023-09-15 10:10:05

R 語(yǔ)言

2010-05-24 09:51:37

System Cent
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)