summaryrefslogtreecommitdiff
path: root/pkg/api/api.go
blob: 6bbdd303c6629ccc67a988b2d5c1b85ff5f392af (plain) (blame)
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
package api

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

	"github.com/go-http-utils/logger"

	"gitrepo.ru/neonxp/idecnode/pkg/config"
	"gitrepo.ru/neonxp/idecnode/pkg/idec"
)

type API struct {
	config *config.Config
	idec   *idec.IDEC
}

func New(i *idec.IDEC, cfg *config.Config) *API {
	return &API{
		config: cfg,
		idec:   i,
	}
}

func (a *API) Run(ctx context.Context) error {
	errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)

	mux := http.NewServeMux()

	mux.HandleFunc(`GET /list.txt`, a.getListHandler)
	mux.HandleFunc(`GET /blacklist.txt`, a.getBlacklistTxtHandler)
	mux.HandleFunc(`GET /u/e/{ids...}`, a.getEchosHandler)
	mux.HandleFunc(`GET /u/m/{ids...}`, a.getBundleHandler)
	mux.HandleFunc(`GET /u/point/{pauth}/{tmsg}`, a.getPointHandler)
	mux.HandleFunc(`POST /u/point`, a.postPointHandler)
	mux.HandleFunc(`GET /m/{msgID}`, a.getMessageHandler)
	mux.HandleFunc(`GET /e/{id}`, a.getEchoHandler)
	mux.HandleFunc(`GET /x/features`, a.getFeaturesHandler)
	mux.HandleFunc(`GET /x/c/{ids...}`, a.getEchosInfo)

	srv := http.Server{
		Addr:     a.config.Listen,
		Handler:  logger.Handler(mux, os.Stdout, logger.Type(a.config.LoggerType)),
		ErrorLog: errorLog,
	}

	go func() {
		<-ctx.Done()
		srv.Close()
	}()
	log.Println("started IDEC node at", a.config.Listen)
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		return err
	}

	return nil
}