add web ui and user route
This commit is contained in:
37
main.go
37
main.go
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"game-wishlist/auth"
|
||||
@@ -15,6 +16,11 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
//go:embed web/dist
|
||||
webOutput embed.FS
|
||||
)
|
||||
|
||||
func sendError(w http.ResponseWriter, msg string, err error, status int) {
|
||||
m := msg
|
||||
if err != nil {
|
||||
@@ -48,6 +54,15 @@ func main() {
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
if path == "/" {
|
||||
path = "/index.html"
|
||||
}
|
||||
filePath := "web/dist" + path
|
||||
http.ServeFileFS(w, r, webOutput, filePath)
|
||||
})
|
||||
|
||||
mux.HandleFunc("POST /api/auth/register", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Login string `json:"login"`
|
||||
@@ -136,6 +151,28 @@ func main() {
|
||||
}{true}, 200)
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /api/user", func(w http.ResponseWriter, r *http.Request) {
|
||||
c, err := r.Cookie("token")
|
||||
if err != nil {
|
||||
sendError(w, "no token cookie", err, 401)
|
||||
return
|
||||
}
|
||||
|
||||
userId, err := auth.ValidateUserToken(c.Value)
|
||||
if err != nil {
|
||||
sendError(w, "invalid token", err, 401)
|
||||
return
|
||||
}
|
||||
|
||||
user := &model.User{}
|
||||
if tx := db.First(user, "id = ?", userId); tx.Error != nil {
|
||||
sendError(w, "user not found", err, 404)
|
||||
return
|
||||
}
|
||||
|
||||
sendJSON(w, user, 200)
|
||||
})
|
||||
|
||||
log.Print("starting http server on http://localhost:5000")
|
||||
if err := http.ListenAndServe(":5000", mux); err != nil {
|
||||
log.Fatalf("failed to start http server: %v\n", err)
|
||||
|
||||
Reference in New Issue
Block a user