summaryrefslogtreecommitdiff
path: root/system/api/push.go
blob: fdce3e2033afa121db3b71ab91f5a634093acc93 (plain)
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
package api

import (
	"log"
	"net/http"
	"strings"

	"github.com/haturatu/ponzu/system/item"

	"github.com/tidwall/gjson"
)

const errRecursivePush = "recursive push not allowed"

func push(res http.ResponseWriter, req *http.Request, pt interface{}, data []byte) {
	// Push(target string, opts *PushOptions) error
	if pusher, ok := res.(http.Pusher); ok {
		if p, ok := pt.(item.Pushable); ok {
			// get fields to pull values from data
			fields, err := p.Push(res, req)
			if err != nil {
				log.Println("[Pushable] error:", err)
				return
			}

			// parse values from data to push
			values := gjson.GetManyBytes(data, fields...)

			// push all values from Pushable items' fields
			for i := range values {
				val := values[i]
				val.ForEach(func(k, v gjson.Result) bool {
					if v.String() == "null" {
						return true
					}

					// check that the push is not to its parent URL
					if v.String() == (req.URL.Path + "?" + req.URL.RawQuery) {
						return true
					}

					err := pusher.Push(v.String(), nil)
					// check for error, "http2: recursive push not allowed"
					// and return, suppressing a log message
					// XXX: errRecursivePush has been co-located to this
					// package instead of importing golang.org/x/net/http2
					// to get the error itself.
					if err != nil && strings.Contains(err.Error(), errRecursivePush) {
						return true
					}
					if err != nil {
						log.Println("Error during Push of value:", v.String(), err)
					}

					return true
				})
			}
		}
	}

}