forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
93 lines (78 loc) · 2.42 KB
/
main.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
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
package main
import (
"database/sql"
"fmt"
stdhttp "net/http"
"os"
"github.com/andskur/go/services/friendbot/internal"
"github.com/andskur/go/support/app"
"github.com/andskur/go/support/config"
"github.com/andskur/go/support/errors"
"github.com/andskur/go/support/http"
"github.com/andskur/go/support/log"
"github.com/andskur/go/support/render/problem"
"github.com/go-chi/chi"
"github.com/spf13/cobra"
)
// Config represents the configuration of a friendbot server
type Config struct {
Port int `toml:"port" valid:"required"`
FriendbotSecret string `toml:"friendbot_secret" valid:"required"`
NetworkPassphrase string `toml:"network_passphrase" valid:"required"`
HorizonURL string `toml:"horizon_url" valid:"required"`
StartingBalance string `toml:"starting_balance" valid:"required"`
TLS *config.TLS `valid:"optional"`
}
func main() {
rootCmd := &cobra.Command{
Use: "friendbot",
Short: "friendbot for the Stellar Test Network",
Long: "client-facing api server for the friendbot service on the Stellar Test Network",
Run: run,
}
rootCmd.PersistentFlags().String("conf", "./friendbot.cfg", "config file path")
rootCmd.Execute()
}
func run(cmd *cobra.Command, args []string) {
var (
cfg Config
cfgPath = cmd.PersistentFlags().Lookup("conf").Value.String()
)
log.SetLevel(log.InfoLevel)
err := config.Read(cfgPath, &cfg)
if err != nil {
switch cause := errors.Cause(err).(type) {
case *config.InvalidConfigError:
log.Error("config file: ", cause)
default:
log.Error(err)
}
os.Exit(1)
}
fb := initFriendbot(cfg.FriendbotSecret, cfg.NetworkPassphrase, cfg.HorizonURL, cfg.StartingBalance)
router := initRouter(fb)
registerProblems()
addr := fmt.Sprintf("0.0.0.0:%d", cfg.Port)
http.Run(http.Config{
ListenAddr: addr,
Handler: router,
TLS: cfg.TLS,
OnStarting: func() {
log.Infof("starting friendbot server - %s", app.Version())
log.Infof("listening on %s", addr)
},
})
}
func initRouter(fb *internal.Bot) *chi.Mux {
mux := http.NewAPIMux(false)
handler := &internal.FriendbotHandler{Friendbot: fb}
mux.Get("/", handler.Handle)
mux.Post("/", handler.Handle)
mux.NotFound(stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
problem.Render(r.Context(), w, problem.NotFound)
}))
return mux
}
func registerProblems() {
problem.RegisterError(sql.ErrNoRows, problem.NotFound)
}