假設您幫助管理一個小型組織或俱樂部,並擁有一個儲存所有成員詳細資訊(姓名、電話、電子郵件...)的資料庫。
在您需要的任何地方都可以存取這些最新資訊不是很好嗎?好吧,有了 CardDAV,你就可以!
CardDAV 是一個得到良好支援的聯絡人管理開放標準;它在 iOS 聯絡人應用程式和許多適用於 Android 的應用程式中具有本機整合。
伺服器端,實作 CardDAV 是一個 http 伺服器,它會回應不尋常的 http 方法(PROPFIND、REPORT 而不是 GET、POST...)。幸運的是,有一個 Go 模組可以大大簡化工作:github.com/emersion/go-webdav。該庫需要一個已實現的後端,並提供一個標準的 http.Handler,該處理程序應在身份驗證後為 HTTP 請求提供服務。
驗證
有趣的是,該程式庫不提供有關用戶身份驗證的任何幫助,但是由於 Go 可組合性,這不是問題。
CardDAV 使用基本驗證憑證。檢查憑證後,我們可以將這些憑證保存在上下文中(稍後會有用):
package main import ( "context" "net/http" "github.com/emersion/go-webdav/carddav" ) type ( ctxKey struct{} ctxValue struct { username string } ) func NewCardDAVHandler() http.Handler { actualHandler := carddav.Handler{ Backend: &ownBackend{}, } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { username, password, ok := r.BasicAuth() // check username and password: adjust the logic to your system (do NOT store passwords in plaintext) if !ok || username != "admin" || password != "s3cr3t" { // abort the request handling on failure w.Header().Add("WWW-Authenticate", `Basic realm="Please authenticate", charset="UTF-8"`) http.Error(w, "HTTP Basic auth is required", http.StatusUnauthorized) return } // user is authenticated: store this info in the context ctx := context.WithValue(r.Context(), ctxKey{}, ctxValue{username}) // delegate the work to the CardDAV handle actualHandler.ServeHTTP(w, r.WithContext(ctx)) }) }
實現 CardDAV 介面
ownBackend結構必須實作carddav.Backend接口,該接口不是很薄,但仍然易於管理。
CurrentUserPrincipal 和 AddressBookHomeSetPath 必須提供 URL(以斜線開頭和結尾)。通常是使用者名稱/聯絡人。這是您需要從上下文中提取使用者名稱的地方(這是唯一可用的參數):
func currentUsername(ctx context.Context) (string, error) { if v, ok := ctx.Value(ctxKey{}).(ctxValue); ok { return v.username, nil } return "", errors.New("not authenticated") } type ownBackend struct{} // must begin and end with a slash func (b *ownBackend) CurrentUserPrincipal(ctx context.Context) (string, error) { username, err := currentUsername(ctx) return "/" + url.PathEscape(username) + "/", err } // must begin and end with a slash as well func (b *ownBackend) AddressBookHomeSetPath(ctx context.Context) (string, error) { principal, err := b.CurrentUserPrincipal(ctx) return principal + "contacts/", err }
之後,樂趣就開始了:您需要實作 AddressBook、GetAddressObject 和 ListAddressObjects 方法。
AddressBook 傳回一個簡單的結構,其中路徑應以上面的 AddressBookHomeSetPath 開頭(並以斜線結尾)
GetAddressObject 和 ListAddressObjects 必須檢查目前路徑(以確保目前經過驗證的使用者可以存取這些聯絡人),然後將聯絡人作為 AddressObject 傳回。
地址對象
AddressObject 有多個屬性,最重要的是:
- 辨識該特定聯絡人的路徑(可以是任意的,以斜線開頭)
- ETag讓客戶端快速檢查是否有更新發生(如果你忘記了,iOS將不會顯示任何內容)
- 需要 VCard 的卡
VCard 代表實際的聯絡人數據,並且可能必須根據您儲存聯絡人的方式進行調整。就我而言,它的結局是這樣的:
func utf8Field(v string) *vcard.Field { return &vcard.Field{ Value: v, Params: vcard.Params{ "CHARSET": []string{"UTF-8"}, }, } } func vcardFromUser(u graphqlient.User) vcard.Card { c := vcard.Card{} c.Set(vcard.FieldFormattedName, utf8Field(u.Firstname+" "+u.Lastname)) c.SetName(&vcard.Name{ Field: utf8Field(""), FamilyName: u.Lastname, GivenName: u.Firstname, }) c.SetRevision(u.UpdatedAt) c.SetValue(vcard.FieldUID, u.Extid) c.Set(vcard.FieldOrganization, utf8Field(u.Unit)) // addFields sorts the key to ensure a stable order addFields := func(fieldName string, values map[string]string) { for _, k := range slices.Sorted(maps.Keys(values)) { v := values[k] c.Add(fieldName, &vcard.Field{ Value: v, Params: vcard.Params{ vcard.ParamType: []string{k + ";CHARSET=UTF-8"}, // hacky but prevent maps ordering issues // "CHARSET": []string{"UTF-8"}, }, }) } } addFields(vcard.FieldEmail, u.Emails) addFields(vcard.FieldTelephone, u.Phones) vcard.ToV4(c) return c }
採用唯讀快捷方式
某些方法允許更新聯絡人。由於我不希望透過 CardDAV 更新我的成員列表,因此我向 Put 和 Delete 方法返回 403 錯誤: return webdav.NewHTTPError(http.StatusForbidden,errors.New("carddav:不支援操作"))
本地測試
iOS 要求 CardDAV 伺服器透過 https 提供服務。您可以使用openssl 在本地產生自簽名憑證(將192.168.XXX.XXX 替換為您的IP 位址),並將其輸入至http.ListenAndServeTLS(addr, "localhost.crt", "localhost.key", NewCardDAVHandler( ))
openssl req -new -subj "/C=US/ST=Utah/CN=192.168.XXX.XXX" -newkey rsa:2048 -nodes -keyout localhost.key -out localhost.csr openssl x509 -req -days 365 -in localhost.csr -signkey localhost.key -out localhost.crt
之後,您應該能夠透過新增指向您自己的 IP 位址和連接埠的「CardDAV 聯絡帳戶」來在本地進行實驗。
結論
在 Go 中實作 CardDAV 伺服器有點複雜,但顯然值得:您的聯絡人將自動與您組織伺服器上的資料同步!
您知道其他允許這種本機整合的很酷的協定嗎?歡迎分享您的經驗!
以上是如何將通訊錄與手機同步?在 Go 中實現 CardDAV!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文解釋了GO的軟件包導入機制:命名imports(例如導入“ fmt”)和空白導入(例如導入_ fmt; fmt;)。 命名導入使包裝內容可訪問,而空白導入僅執行t

本文詳細介紹了MySQL查詢結果的有效轉換為GO結構切片。 它強調使用數據庫/SQL的掃描方法來最佳性能,避免手動解析。 使用DB標籤和Robus的結構現場映射的最佳實踐

本文解釋了Beego的NewFlash()函數,用於Web應用程序中的頁間數據傳輸。 它專注於使用newflash()在控制器之間顯示臨時消息(成功,錯誤,警告),並利用會話機制。 Lima

本文探討了GO的仿製藥自定義類型約束。 它詳細介紹了界面如何定義通用功能的最低類型要求,從而改善了類型的安全性和代碼可重複使用性。 本文還討論了局限性和最佳實踐

本文演示了創建模擬和存根進行單元測試。 它強調使用接口,提供模擬實現的示例,並討論最佳實踐,例如保持模擬集中並使用斷言庫。 文章

本文詳細介紹了在GO中詳細介紹有效的文件,將OS.WriteFile(適用於小文件)與OS.openfile和緩衝寫入(最佳大型文件)進行比較。 它強調了使用延遲並檢查特定錯誤的可靠錯誤處理。

本文使用跟踪工具探討了GO應用程序執行流。 它討論了手冊和自動儀器技術,比較諸如Jaeger,Zipkin和Opentelemetry之類的工具,並突出顯示有效的數據可視化


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版
SublimeText3 Linux最新版

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

WebStorm Mac版
好用的JavaScript開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!