-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom.go
68 lines (53 loc) · 1.31 KB
/
random.go
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
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/shitpostingio/randomapi/backstore"
"github.com/google/uuid"
"github.com/shitpostingio/randomapi/rest/client"
"go.mongodb.org/mongo-driver/mongo"
)
// Random will return a random post
func random(w http.ResponseWriter, r *http.Request) {
post, err := getRandomPost(postCollection)
if err != nil {
writeError(w, err, http.StatusBadRequest)
return
}
err = json.NewEncoder(w).Encode(post)
if err != nil {
writeError(w, err, http.StatusInternalServerError)
}
return
}
func getRandomPost(collection *mongo.Collection) (client.Response, error) {
post, err := backstore.FindRandomPost(collection)
if err != nil {
return client.Response{}, err
}
postID := uuid.New().String()
var ext string
if post.Media.Type == "photo" {
ext = "jpg"
} else {
ext = "mp4"
}
filename := fmt.Sprintf("%s.%s", post.Media.FileID, ext)
randompost := client.Response{
ID: postID,
Post: client.Data{
URL: fmt.Sprintf("%s/storage/%s", c.Endpoint, filename),
Filename: filename,
Type: post.Media.Type,
Date: post.PostedAt,
},
}
requestedPosts[filename] = requestedPost{
path: fmt.Sprintf("%s/%s", c.PostFolder, filename),
mediatype: post.Media.Type,
requestdate: time.Now(),
}
return randompost, nil
}