DEVELOPMENT ENVIRONMENT

~liljamo/felu

ref: 9c727c0722503a714cb691b9549fbff47937a0d6 felu/felu.go -rw-r--r-- 2.1 KiB
9c727c07Jonni Liljamo feat: version api endpoint 1 year, 30 days 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
96
97
98
99
100
101
102
103
/*
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */
package main

import (
	"log"
	"net/http"
	"strconv"
	"time"

	"git.src.quest/~skye/felu-ddns/config"
	"git.src.quest/~skye/felu-ddns/db"
	"git.src.quest/~skye/felu-ddns/dns"
	"github.com/gin-gonic/gin"
	"golang.org/x/sync/errgroup"
)

var version = "notset-builtin"

var (
	g errgroup.Group
)

func setupFrontendRouter() *gin.Engine {
	r := gin.Default()
	r.Static("/static", "./static")
	r.HTMLRender = &TemplRender{}

	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "", index())
	})

	return r
}

func setupBackendRouter() *gin.Engine {
	r := gin.Default()

	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status": "success",
		})
	})

	r.GET("/version", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"version": version,
		})
	})

	return r
}

func main() {
	log.Print("[felu] Starting up...")

	config.InitConfig()

	if err := db.InitDB(); err != nil {
		log.Fatalf("[felu] Failed to initialize database: '%s'", err)
	}
	defer db.DBConn.Close()

	frontend := &http.Server{
		Addr: config.FeluConfig.FrontendBindAddr,
		Handler: setupFrontendRouter(),
		ReadTimeout: 5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	backend := &http.Server{
		Addr: config.FeluConfig.BackendBindAddr,
		Handler: setupBackendRouter(),
		ReadTimeout: 5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	log.Printf("[felu] Serving frontend at '%s'", config.FeluConfig.FrontendBindAddr)
	g.Go(func() error {
		return frontend.ListenAndServe()
	})

	log.Printf("[felu] Serving backend at '%s'", config.FeluConfig.BackendBindAddr)
	g.Go(func() error {
		return backend.ListenAndServe()
	})

	dnsIP := config.FeluConfig.DNSBindIP
	dnsPort := strconv.Itoa(int(config.FeluConfig.DNSBindPort))
	dnsAddr := dnsIP + ":" + dnsPort
	log.Printf("[felu] Serving DNS at '%s'", dnsAddr)
	g.Go(func() error {
		return dns.Run(dnsAddr)
	})

	if err := g.Wait(); err != nil {
		log.Fatalf("[felu] Error while running: %s", err)
	}
}