logs.go 1.13 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4
package corehttp

import (
	"io"
5
	"net"
Jeromy's avatar
Jeromy committed
6 7
	"net/http"

tavit ohanian's avatar
tavit ohanian committed
8 9
	core "gitlab.dms3.io/dms3/go-dms3/core"
	// lwriter "gitlab.dms3.io/dms3/go-log/writer"
Jeromy's avatar
Jeromy committed
10 11 12 13 14 15 16
)

type writeErrNotifier struct {
	w    io.Writer
	errs chan error
}

17
func newWriteErrNotifier(w io.Writer) (io.WriteCloser, <-chan error) {
Jeromy's avatar
Jeromy committed
18 19 20 21 22 23 24 25 26 27
	ch := make(chan error, 1)
	return &writeErrNotifier{
		w:    w,
		errs: ch,
	}, ch
}

func (w *writeErrNotifier) Write(b []byte) (int, error) {
	n, err := w.w.Write(b)
	if err != nil {
Jeromy's avatar
Jeromy committed
28 29 30 31
		select {
		case w.errs <- err:
		default:
		}
Jeromy's avatar
Jeromy committed
32
	}
Jeromy's avatar
Jeromy committed
33 34 35
	if f, ok := w.w.(http.Flusher); ok {
		f.Flush()
	}
Jeromy's avatar
Jeromy committed
36 37 38
	return n, err
}

39 40 41 42 43 44 45 46
func (w *writeErrNotifier) Close() error {
	select {
	case w.errs <- io.EOF:
	default:
	}
	return nil
}

Jeromy's avatar
Jeromy committed
47
func LogOption() ServeOption {
tavit ohanian's avatar
tavit ohanian committed
48
	return func(n *core.Dms3Node, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {
Jeromy's avatar
Jeromy committed
49 50
		mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(200)
tavit ohanian's avatar
tavit ohanian committed
51 52 53 54 55
			// wnf, errs := newWriteErrNotifier(w)
			// lwriter.WriterGroup.AddWriter(wnf)
			// log.Event(n.Context(), "log API client connected") //nolint deprecated
			// <-errs
			log.Debugf("log API client connected")
Jeromy's avatar
Jeromy committed
56 57 58 59
		})
		return mux, nil
	}
}