68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package routers
|
|
|
|
import (
|
|
"fmt"
|
|
"main/models"
|
|
"main/utils"
|
|
"net/http"
|
|
)
|
|
|
|
// 獲取當前賬戶信息(重寫, 爲輸出增加sid字段)
|
|
func AccountGet(w http.ResponseWriter, r *http.Request) {
|
|
var account struct {
|
|
ID int `json:"id"`
|
|
Name string `json:"name"`
|
|
Email string `json:"email"`
|
|
SessionID string `json:"session_id"`
|
|
CreatedAt string `json:"created_at"`
|
|
UpdatedAt string `json:"updated_at"`
|
|
}
|
|
|
|
// 獲取Cookie
|
|
cookie, err := r.Cookie("session_id")
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
|
|
// 獲取會話
|
|
session := models.Session{ID: cookie.Value}
|
|
session.Get()
|
|
|
|
// 獲取用戶
|
|
user := models.User{ID: session.UserID}
|
|
user.Get()
|
|
|
|
account.ID = user.ID
|
|
account.Name = user.Name
|
|
account.Email = user.Email
|
|
account.SessionID = session.ID
|
|
account.CreatedAt = user.CreatedAt
|
|
account.UpdatedAt = user.UpdatedAt
|
|
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.Write(utils.ToJSON(account))
|
|
}
|
|
|
|
// 獲取當前賬戶, 並將其傳入回調函數
|
|
func get_account(w http.ResponseWriter, r *http.Request, callback func(*models.User)) (err error) {
|
|
// 獲取Cookie
|
|
cookie, err := r.Cookie("session_id")
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return nil
|
|
}
|
|
|
|
// 獲取會話
|
|
session := models.Session{ID: cookie.Value}
|
|
session.Get()
|
|
|
|
// 獲取用戶
|
|
user := models.User{ID: session.UserID}
|
|
user.Get()
|
|
|
|
callback(&user)
|
|
|
|
return nil
|
|
}
|