~yerinalexey/gobin

ref: 478164c98843185c65508a38552befc51838da7b gobin/paste/paste.go -rw-r--r-- 1.9 KiB
478164c9 — Alexey Yerin Add option to set log file 9 months ago
                                                                                
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
82
83
84
85
86
87
88
89
90
91
92
93
94
package paste

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"github.com/gorilla/mux"
	"github.com/jackc/pgx/v4/pgxpool"
)

type Paste struct {
	Id       int
	Contents string
	Public   bool
}

type PublicPaste struct {
	Id      int
	Summary string
	Link    string
}

// Get paste by it's id. Returns nil and error if paste does not exist.
func GetById(pool *pgxpool.Pool, id int) (*Paste, error) {
	var contents string
	var public bool

	err := pool.QueryRow(context.Background(), `select contents, public from pastes where id=$1`, id).Scan(&contents, &public)

	if err != nil {
		return nil, err
	}

	return &Paste{id, contents, public}, nil

}

// Insert a new paste
func Insert(pool *pgxpool.Pool, contents string, public bool) (int, error) {
	var id int

	err := pool.QueryRow(context.Background(), `insert into pastes (contents, public) values ($1, $2) returning id`, contents, public).Scan(&id)

	// id is 0 by default so returning like this is fine
	return id, err
}

// Get list of public pastes
func GetPublicPastes(pool *pgxpool.Pool, router *mux.Router) ([]PublicPaste, error) {
	query, err := pool.Query(context.Background(), `select id, contents from pastes where public=true;`)

	if err != nil {
		return nil, err
	}

	pastes := []PublicPaste{}

	for query.Next() {
		var id int
		var contents string

		err := query.Scan(&id, &contents)

		if err != nil {
			return nil, err
		}

		// Get only first 15 lines
		// TODO: Configure that value
		summary := strings.Join(strings.Split(contents, "\n")[:15], "\n")

		link, err := router.Get("paste").URL("id", strconv.Itoa(id))

		if err != nil {
			return nil, err
		}

		pastes = append(pastes, PublicPaste{id, summary, link.String()})
	}

	return pastes, nil
}

// CreatePermalink creates an absolute link to a paste
func CreatePermalink(id int, host string, insecure bool) string {
	protocol := "https"
	if insecure {
		protocol = "http"
	}

	return fmt.Sprintf("%s://%s/paste/%d", protocol, host, id)
}