DEVELOPMENT ENVIRONMENT

~liljamo/emerwen-web

ref: a20635584f23b381e2f025219d48ef23f2f13324 emerwen-web/internal/config/config.go -rw-r--r-- 2.1 KiB
a2063558Jonni Liljamo chore: update flake inputs 4 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
/*
 * Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under GPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */

// Package config provides a Config type and parsing function.
package config

import (
	"flag"
	"fmt"
	"os"
	"strings"
)

// Config holds application configuration values.
type Config struct {
	BindAddr string

	OIDCClientID     string
	OIDCClientSecret string
	// protocol://domain.tld/oauth2/oidc/callback
	OIDCRedirectURL string
	OIDCProvider    string
}

// ParseFromArgs parses program flags into a Config.
// Panics if certain required values are not provided, or when fails to read
// a file.
func ParseFromArgs() Config {
	bindAddrPtr := flag.String("bind_address", "127.0.0.1:3000", "bind address")

	oidcClientIDPtr := flag.String("oidc_client_id", "emerwen", "OIDC client ID")
	oidcClientIDFilePtr := flag.String("oidc_client_id_file", "", "OIDC client ID file")
	oidcClientSecretFilePtr := flag.String("oidc_client_secret_file", "", "OIDC client secret file")
	oidcRedirectURLPtr := flag.String("oidc_redirect_url", "", "OIDC redirect URL")
	oidcProviderPtr := flag.String("oidc_provider", "", "OIDC provider")

	flag.Parse()

	var oidcClientID string
	if *oidcClientIDFilePtr == "" {
		oidcClientID = *oidcClientIDPtr
	} else {
		b, err := os.ReadFile(*oidcClientIDFilePtr)
		if err != nil {
			panic(fmt.Sprintf("failed to read oidc_client_id_file: %s", err))
		}
		oidcClientID = strings.TrimSpace(string(b))
	}

	var oidcClientSecret string
	if *oidcClientSecretFilePtr == "" {
		panic("oidc_client_secret_file is required")
	}
	b, err := os.ReadFile(*oidcClientSecretFilePtr)
	if err != nil {
		panic(fmt.Sprintf("failed to read oidc_client_secret_file: %s", err))
	}
	oidcClientSecret = strings.TrimSpace(string(b))

	if *oidcRedirectURLPtr == "" {
		panic("oidc_redirect_url is required")
	}

	if *oidcProviderPtr == "" {
		panic("oidc_endpoint is required")
	}

	return Config{
		BindAddr: *bindAddrPtr,

		OIDCClientID:     oidcClientID,
		OIDCClientSecret: oidcClientSecret,
		OIDCRedirectURL:  *oidcRedirectURLPtr,
		OIDCProvider:     *oidcProviderPtr,
	}
}