~evanj/evanjon.es

ref: 420d2707f2d423977b12534af72c1c90c8dddbe2 evanjon.es/internal/c/search/search.go -rw-r--r-- 1.8 KiB
420d2707Evan M Jones Feat(prev/next): Adding previous and next post links. 1 year, 6 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
95
package search

import (
	"context"
	"log"
	"net/http"

	"git.sr.ht/~evanj/evanjon.es/internal/c"
	"git.sr.ht/~evanj/evanjon.es/internal/m/content"
	"git.sr.ht/~evanj/evanjon.es/internal/s/tmpl"
)

var (
	ItemHTML = tmpl.MustParse("html/item.html")
)

type SearchEndpoint struct {
	*c.Endpoint
	log                *log.Logger
	cms                cmsProvider
	typePage, typePost int
}

type cmsProvider interface {
	Find(ctx context.Context, typeID int, field, query string) (content.Content, error)
}

func New(base *c.Endpoint, log *log.Logger, cms cmsProvider, typePage, typePost int) *SearchEndpoint {
	return &SearchEndpoint{
		base,
		log,
		cms,
		typePage, typePost,
	}
}

func (e *SearchEndpoint) search(ctx context.Context, slug string) (content.Content, error) {

	do := func(ctx context.Context, typ int, slug string, ch chan content.Content, ech chan error) {
		c, err := e.cms.Find(ctx, typ, "slug", slug)
		if err != nil {
			ech <- err
			return
		}
		ch <- c
	}

	contentCh := make(chan content.Content)
	errCh := make(chan error)

	go do(ctx, e.typePost, slug, contentCh, errCh)
	go do(ctx, e.typePost, slug, contentCh, errCh)

	errcount := 0

	for {
		select {

		case c := <-contentCh:
			return c, nil

		case err := <-errCh:
			errcount++
			if errcount > 1 {
				return nil, err
			}
			break
		}
	}
}

func (e *SearchEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx := e.ContextTimeout(r)

	slug := "ahoj"
	path := r.URL.Path[1:]
	if path != "" {
		slug = path
	}

	e.log.Println("searching for content with slug of:", slug)

	c, err := e.search(ctx, slug)
	if err != nil {
		e.log.Println("failed to find content", err)
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte("failed to find content"))
		return
	}

	e.HTML(w, r, ItemHTML, map[string]interface{}{
		"Item":     c,
		"ShowDate": c.Type() != e.typePage,
	})
}