Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# flyctl launch added from .gitignore
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore

# SQLite database files
**/*.db

# Binaries for programs and plugins
**/bin
**/*.exe
**/*.exe~
**/*.dll
**/*.so
**/*.dylib

# Test binary, built with `go test -c`
**/*.test

# Output of the go coverage tool, specifically when used with LiteIDE
**/*.out

# Dependency directories (remove the comment below to include it)
**/vendor

# Go workspace file
**/go.work
**/*.sqlite

# Nix related
**/.direnv
**/result

# Build artifact generated by Makefile
**/.generate.marker

**/tmp

**/.env
**/.DS_Store
fly.toml
18 changes: 18 additions & 0 deletions .github/workflows/fly-deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# See https://fly.io/docs/app-guides/continuous-deployment-with-github-actions/

name: Fly Deploy
on:
push:
branches:
- main
jobs:
deploy:
name: Deploy app
runs-on: ubuntu-latest
concurrency: deploy-group # optional: ensure only one action runs at a time
steps:
- uses: actions/checkout@v4
- uses: superfly/flyctl-actions/setup-flyctl@master
- run: flyctl deploy --remote-only
env:
FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
21 changes: 21 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
ARG GO_VERSION=1
FROM golang:${GO_VERSION}-bookworm AS builder

WORKDIR /usr/src/app
COPY go.mod go.sum ./
RUN go mod download && go mod verify
COPY . .
RUN go build -v -o /run-app ./cmd/acmcsuf-api
Comment thread
TheJolman marked this conversation as resolved.
Resolved


FROM debian:bookworm

COPY --from=builder /run-app /usr/local/bin/
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /app/data
WORKDIR /app
COPY --from=builder /usr/src/app/sql/migrations ./sql/migrations
EXPOSE 8080
CMD ["run-app"]
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ api: $(BIN_DIR)/$(API_NAME) ## Build the api binary

$(BIN_DIR)/$(API_NAME): $(GO_DEPS) sqlc
@mkdir -p $(BIN_DIR)
go build -x -ldflags "-X main.Version=$(VERSION)" -o $(BIN_DIR)/$(API_NAME) ./cmd/$(API_NAME)
go build -ldflags "-X main.Version=$(VERSION)" -o $(BIN_DIR)/$(API_NAME) ./cmd/$(API_NAME)

cli: $(BIN_DIR)/$(CLI_NAME) ## Build the cli binary

$(BIN_DIR)/$(CLI_NAME): $(GO_DEPS)
@mkdir -p $(BIN_DIR)
go build -x -ldflags "-X cli.Version=$(VERSION)" -o $(BIN_DIR)/$(CLI_NAME) ./cmd/$(CLI_NAME)
go build -ldflags "-X cli.Version=$(VERSION)" -o $(BIN_DIR)/$(CLI_NAME) ./cmd/$(CLI_NAME)

generate: swag sqlc ## Generate all necessary files

Expand Down
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,20 @@ Use "acmcsuf-cli [command] --help" for more information about a command.
```

#### Configuring the CLI
The CLI's auth-related configuration is currently handled via environment variables similarly to the API. Other settings can be configured by modifiying the config file, located at `~/.config/acmcsuf-cli/config.json`.
The CLI's auth-related configuration is currently handled via environment variables similarly to the API. Other settings can be configured by modifying `~/.config/acmcsuf-cli/config.json`:

```json
{
"api_url": "http://localhost:8080",
"log_level": "info"
}
```

Override the configured API for one command with `--api-url`, for example:

```sh
acmcsuf-cli events post --api-url https://api-acmcsuf-com-black-wind-9210.fly.dev
```

### Other useful commands from the Makefile

Expand Down
14 changes: 14 additions & 0 deletions docs/docker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Useful docker commands

```sh
# build
docker build -t acmcsuf-api:latest .

# run
docker run --rm \
--name acmcsuf-api \
--mount type=volume,source=sqlite_data,target=/app/data \
-p 8080:8080 \
acmcsuf-api:latest

```
34 changes: 34 additions & 0 deletions fly.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# fly.toml app configuration file generated for api-acmcsuf-com-black-wind-9210 on 2026-08-01T19:15:18-07:00
#
# See https://fly.io/docs/reference/configuration/ for information about how to use this file.
#

app = 'api-acmcsuf-com-black-wind-9210'
primary_region = 'lax'

[build]
[build.args]
GO_VERSION = '1.25.0'

[env]
PORT = '8080'
DATABASE_URL= 'file:/app/data/acmcsuf.db?cache=shared&mode=rwc'
GIN_MODE = 'debug'
ENV = 'development'

[http_service]
internal_port = 8080
force_https = true
auto_stop_machines = 'stop'
auto_start_machines = true
min_machines_running = 1
processes = ['app']

[[vm]]
memory = '256m'
cpu_kind = 'shared'
cpus = 1

[mounts]
source = "sqlite_data"
destination = "/app/data"
2 changes: 1 addition & 1 deletion internal/api/routes/v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func SetupV1(router *gin.Engine, eventService services.EventsServicer,

var botSession *discordgo.Session
var err error
if cfg.DiscordBotToken != "" {
if cfg.DiscordBotToken != "" && cfg.Env != "development" {
botSession, err = discordgo.New("Bot " + cfg.DiscordBotToken)
if err != nil {
log.Fatalf("%v", err)
Expand Down
8 changes: 4 additions & 4 deletions internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ func Run(ctx context.Context) {

go func() {
serverAddr := ":" + cfg.Port
if cfg.Env == "development" {
// this binds the server to the loopback interface in dev mode for security reasons
serverAddr = "localhost:" + cfg.Port
}
// if cfg.Env == "development" {
// this binds the server to the loopback interface in dev mode for security reasons
// serverAddr = "localhost:" + cfg.Port
// }

if err := router.Run(serverAddr); err != nil {
log.Fatalf("Failed to start server: %v", err)
Expand Down
5 changes: 1 addition & 4 deletions internal/cli/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ func SendRequestAndReadResponse(url *url.URL, enableAuth bool, method string, bo
func CheckConnection(url string) error {
_, err := http.Get(url)
if err != nil {
// fang/lipgloss lowk nukes this custom formatting
return fmt.Errorf("\x1b[1;37;41mUNABLE TO CONNECT\x1b[0m | %s\n\t↳ %v",
"Did you forget to start the server?",
err)
return fmt.Errorf("UNABLE TO CONNECT: %v", err)
}
return nil
}
28 changes: 7 additions & 21 deletions internal/cli/command/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,42 +28,28 @@ const (

var Version = "dev"

var overrides *config.ConfigOverrides

var rootCmd = &cobra.Command{
Use: os.Args[0],
Short: "A CLI tool to help manage the API of the CSUF ACM website",
}

// init() is a special function that always gets run before main
func init() {
overrides = &config.ConfigOverrides{
Host: "",
Port: "",
}

var err error
config.Cfg, err = config.Load(overrides)
if err != nil {
fmt.Printf("failed to load config: %s", err)
return
}

rootCmd.AddCommand(events.CLIEvents)
rootCmd.AddCommand(officers.CLIOfficers)
rootCmd.AddCommand(config.ConfigCmd)

rootCmd.PersistentFlags().String("host", "", "API server hostname (overrides config)")
rootCmd.PersistentFlags().String("port", "", "API server port (overrides config)")
rootCmd.PersistentFlags().String("api-url", "", "API base URL (overrides config)")

rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
overrides = &config.ConfigOverrides{
Host: cmd.Flag("host").Value.String(),
Port: cmd.Flag("port").Value.String(),
apiURL, err := cmd.Flags().GetString("api-url")
if err != nil {
return fmt.Errorf("failed to read API URL flag: %w", err)
}
config.Cfg, err = config.Load(overrides)

config.Cfg, err = config.Load(apiURL)
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
return fmt.Errorf("failed to load API configuration: %w", err)
}

url := config.GetBaseURL(config.Cfg).JoinPath("health")
Expand Down
5 changes: 3 additions & 2 deletions internal/cli/config/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import (
)

var ConfigCmd = &cobra.Command{
Use: "config <subcommand>",
Short: "Manage this tool's persistent configuration.",
Use: "config <subcommand>",
Short: "Manage this tool's persistent configuration.",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error { return nil },
}

func init() {
Expand Down
32 changes: 12 additions & 20 deletions internal/cli/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,17 @@ import (
)

type Config struct {
Host string `json:"host"`
Port string `json:"port"`
APIURL string `json:"api_url"`
LogLevel string `json:"log_level"`
}

// Subset of Config struct that can be overridden with command line flags
type ConfigOverrides struct {
Host string
Port string
}

var defaultConfig = Config{
Host: "localhost",
Port: "8080",
APIURL: "http://localhost:8080",
LogLevel: "info",
}

// Global config variable
var Cfg *Config
var CfgOverride ConfigOverrides

func init() {
Cfg = &Config{}
Expand All @@ -37,12 +28,11 @@ func init() {
// Loads config with three layers of precedence
// 1. Start with default config
// 2. Load values from config file if present
// 3. Provide any overrides passed in through command line flags (if any)
func Load(overrides *ConfigOverrides) (*Config, error) {
// 3. Apply the API URL override passed on the command line (if any)
func Load(apiURLOverride string) (*Config, error) {
// Load default config
cfg := &Config{
Host: defaultConfig.Host,
Port: defaultConfig.Port,
APIURL: defaultConfig.APIURL,
LogLevel: defaultConfig.LogLevel,
}

Expand All @@ -59,13 +49,15 @@ func Load(overrides *ConfigOverrides) (*Config, error) {
}
}

// Override with args passed with command line args
if overrides.Host != "" {
cfg.Host = overrides.Host
if apiURLOverride != "" {
cfg.APIURL = apiURLOverride
}
if overrides.Port != "" {
cfg.Port = overrides.Port

apiURL, err := NormalizeAPIURL(cfg.APIURL)
if err != nil {
return nil, err
}
cfg.APIURL = apiURL

return cfg, nil
}
Expand Down
29 changes: 25 additions & 4 deletions internal/cli/config/url.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,33 @@ package config
import (
"fmt"
"net/url"
"strings"
)

// Intended to be used with .JoinPath() to construct URLs with configured host:port
// Intended to be used with .JoinPath() to construct URLs
func GetBaseURL(cfg *Config) *url.URL {
return &url.URL{
Scheme: "http",
Host: fmt.Sprintf("%s:%s", cfg.Host, cfg.Port),
apiURL, _ := url.Parse(cfg.APIURL)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

omg trusting the Normalize func with your life 😭 . I would say potential nil pointer but the normalize func does a pretty good job at catching bad urls.

return apiURL
}

func NormalizeAPIURL(rawURL string) (string, error) {
apiURL, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil {
return "", fmt.Errorf("invalid API URL: %w", err)
}
if apiURL.Scheme != "http" && apiURL.Scheme != "https" {
return "", fmt.Errorf("API URL must use http or https")
}
if apiURL.Host == "" {
return "", fmt.Errorf("API URL must include a host")
}
if apiURL.User != nil || apiURL.RawQuery != "" || apiURL.Fragment != "" {
return "", fmt.Errorf("API URL must not include credentials, a query, or a fragment")
}
if apiURL.Path != "" && apiURL.Path != "/" {
return "", fmt.Errorf("API URL must not include a path")
}

apiURL.Path = ""
return apiURL.String(), nil
}
2 changes: 2 additions & 0 deletions nix/shell.nix
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
sqlite,
sqlite-web,
nilaway,
flyctl,
isCI ? false,
full ? false,
}: let
Expand All @@ -38,6 +39,7 @@ in
sqlite
cobra-cli
delve # Go debugger
flyctl
]
# Heavyweight or rarely used tools go here
++ lib.optionals full [
Expand Down
Loading