-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpost_handler.go
More file actions
81 lines (76 loc) · 2.18 KB
/
post_handler.go
File metadata and controls
81 lines (76 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"bytes"
"fmt"
"html/template"
"log"
"net/http"
"time"
"github.com/ABuarque/i2m/auth"
"github.com/ABuarque/i2m/db"
"github.com/ABuarque/i2m/twitter"
"github.com/labstack/echo"
)
func createPostPage(authService *auth.Auth) echo.HandlerFunc {
return func(c echo.Context) error {
authorization := c.QueryParam("authorization")
if authorization == "" {
return c.JSON(http.StatusForbidden, "Acesso negado!")
}
ok, err := authService.IsValid(authorization)
if !ok || err != nil {
return c.JSON(http.StatusForbidden, "Acesso negado!")
}
template := template.Must(template.ParseFiles("templates/createPost.html"))
var html bytes.Buffer
data := struct {
Authorization string
}{
authorization,
}
err = template.Execute(&html, data)
if err != nil {
return c.HTML(http.StatusOK, "<h1>Error</h1>")
}
return c.HTML(http.StatusOK, string(html.Bytes()))
}
}
func createPostHandler(client *db.Client, authService *auth.Auth, twitterService *twitter.Client) echo.HandlerFunc {
return func(c echo.Context) error {
authorization := c.QueryParam("authorization")
if authorization == "" {
return c.JSON(http.StatusForbidden, "Acesso negado!")
}
ok, err := authService.IsValid(authorization)
if !ok || err != nil {
return c.JSON(http.StatusForbidden, "Acesso negado!")
}
r := c.Request()
title := r.FormValue("title")
info := r.FormValue("info")
link := r.FormValue("link")
post := db.Post{
Title: title,
Info: info,
Link: link,
Date: getDate(),
CreatedAt: time.Now(),
}
_, err = client.SavePost(&post)
if err != nil {
log.Println(fmt.Sprintf("failed to save post on db, got %q", err))
return c.HTML(http.StatusOK, "<h1>Error</h1>")
}
tweet := fmt.Sprintf("checkout my new post: %s", link)
err = twitterService.Post(tweet)
if err != nil {
log.Println(fmt.Sprintf("failed to make tweet, got error %q", err))
}
log.Println(fmt.Sprintf("new tweet made: %s ", tweet))
return c.Redirect(http.StatusFound, fmt.Sprintf("/dashboard?authorization=%s", authorization))
}
}
func getDate() string {
year, month, _ := time.Now().Date()
return fmt.Sprintf("%s, %d", month.String(), year)
}