From a1f49af1d93bccdd56d4538b149884418bd2ca2c Mon Sep 17 00:00:00 2001 From: r Date: Fri, 20 Dec 2019 18:30:20 +0000 Subject: Add user page and follow/unfollow calls --- service/transport.go | 60 +++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 52 insertions(+), 8 deletions(-) (limited to 'service/transport.go') diff --git a/service/transport.go b/service/transport.go index 1326c58..6759fcc 100644 --- a/service/transport.go +++ b/service/transport.go @@ -15,14 +15,6 @@ var ( cookieAge = "31536000" ) -func getContextWithSession(ctx context.Context, req *http.Request) context.Context { - sessionID, err := req.Cookie("session_id") - if err != nil { - return ctx - } - return context.WithValue(ctx, "session_id", sessionID.Value) -} - func NewHandler(s Service, staticDir string) http.Handler { r := mux.NewRouter() @@ -192,6 +184,50 @@ func NewHandler(s Service, staticDir string) http.Handler { } }).Methods(http.MethodGet) + r.HandleFunc("/user/{id}", func(w http.ResponseWriter, req *http.Request) { + ctx := getContextWithSession(context.Background(), req) + + id, _ := mux.Vars(req)["id"] + maxID := req.URL.Query().Get("max_id") + minID := req.URL.Query().Get("min_id") + + err := s.ServeUserPage(ctx, w, nil, id, maxID, minID) + if err != nil { + s.ServeErrorPage(ctx, w, err) + return + } + }).Methods(http.MethodGet) + + r.HandleFunc("/follow/{id}", func(w http.ResponseWriter, req *http.Request) { + ctx := getContextWithSession(context.Background(), req) + + id, _ := mux.Vars(req)["id"] + + err := s.Follow(ctx, w, nil, id) + if err != nil { + s.ServeErrorPage(ctx, w, err) + return + } + + w.Header().Add("Location", req.Header.Get("Referer")) + w.WriteHeader(http.StatusFound) + }).Methods(http.MethodPost) + + r.HandleFunc("/unfollow/{id}", func(w http.ResponseWriter, req *http.Request) { + ctx := getContextWithSession(context.Background(), req) + + id, _ := mux.Vars(req)["id"] + + err := s.UnFollow(ctx, w, nil, id) + if err != nil { + s.ServeErrorPage(ctx, w, err) + return + } + + w.Header().Add("Location", req.Header.Get("Referer")) + w.WriteHeader(http.StatusFound) + }).Methods(http.MethodPost) + r.HandleFunc("/signout", func(w http.ResponseWriter, req *http.Request) { // TODO remove session from database w.Header().Add("Set-Cookie", fmt.Sprintf("session_id=;max-age=0")) @@ -202,6 +238,14 @@ func NewHandler(s Service, staticDir string) http.Handler { return r } +func getContextWithSession(ctx context.Context, req *http.Request) context.Context { + sessionID, err := req.Cookie("session_id") + if err != nil { + return ctx + } + return context.WithValue(ctx, "session_id", sessionID.Value) +} + func getMultipartFormValue(mf *multipart.Form, key string) (val string) { vals, ok := mf.Value[key] if !ok { -- cgit v1.2.3