Skip to content
Permalink
Browse files

07-Profile-Page add profile

  • Loading branch information...
bonfy committed Sep 27, 2018
1 parent 2940d8a commit db97f9013662e1a3de2c029937f13b52dc9ac202
Showing with 65 additions and 4 deletions.
  1. +25 −4 controller/home.go
  2. +1 −0 templates/_base.html
  3. +11 −0 templates/content/profile.html
  4. +28 −0 vm/profile.go
@@ -1,19 +1,25 @@
package controller

import (
"fmt"
"log"
"net/http"

"github.com/bonfy/go-mega-code/vm"
"github.com/gorilla/mux"
)

type home struct{}

func (h home) registerRoutes() {
http.HandleFunc("/logout", middleAuth(logoutHandler))
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/register", registerHandler)
http.HandleFunc("/", middleAuth(indexHandler))
r := mux.NewRouter()
r.HandleFunc("/logout", middleAuth(logoutHandler))
r.HandleFunc("/login", loginHandler)
r.HandleFunc("/register", registerHandler)
r.HandleFunc("/user/{username}", middleAuth(profileHandler))
r.HandleFunc("/", middleAuth(indexHandler))

http.Handle("/", r)
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
@@ -85,3 +91,18 @@ func logoutHandler(w http.ResponseWriter, r *http.Request) {
clearSession(w, r)
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
}

func profileHandler(w http.ResponseWriter, r *http.Request) {
tpName := "profile.html"
vars := mux.Vars(r)
pUser := vars["username"]
sUser, _ := getSessionUser(r)
vop := vm.ProfileViewModelOp{}
v, err := vop.GetVM(sUser, pUser)
if err != nil {
msg := fmt.Sprintf("user ( %s ) does not exist", pUser)
w.Write([]byte(msg))
return
}
templates[tpName].Execute(w, &v)
}
@@ -11,6 +11,7 @@
Blog:
<a href="/">Home</a>
{{if .CurrentUser}}
<a href="/user/{{.CurrentUser}}">Profile</a>
<a href="/logout">Logout</a>
{{else}}
<a href="/login">Login</a>
@@ -0,0 +1,11 @@
{{define "content"}}
<h1>User: {{.ProfileUser.Username}}</h1>

<hr/>

{{range .Posts}}
<p>
{{ .User.Username }} says: <b>{{ .Body }}</b>
</p>
{{end}}
{{end}}
@@ -0,0 +1,28 @@
package vm

import "github.com/bonfy/go-mega-code/model"

// ProfileViewModel struct
type ProfileViewModel struct {
BaseViewModel
Posts []model.Post
ProfileUser model.User
}

// ProfileViewModelOp struct
type ProfileViewModelOp struct{}

// GetVM func
func (ProfileViewModelOp) GetVM(sUser, pUser string) (ProfileViewModel, error) {
v := ProfileViewModel{}
v.SetTitle("Profile")
u1, err := model.GetUserByUsername(pUser)
if err != nil {
return v, err
}
posts, _ := model.GetPostsByUserID(u1.ID)
v.ProfileUser = *u1
v.Posts = *posts
v.SetCurrentUser(sUser)
return v, nil
}

0 comments on commit db97f90

Please sign in to comment.
You can’t perform that action at this time.