Some stuff I've used before and will likely use again.
Last active
June 17, 2025 15:44
-
-
Save coolaj86/3bac1e4448a7647e8be5435572f7354a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# debug: goreleaser release --snapshot --clean --skip=publish | |
# release: goreleaser release --clean | |
version: 2 | |
project_name: overclockedmusicd | |
before: | |
hooks: | |
- go mod download | |
- go generate ./... | |
builds: | |
- id: ocmd-all | |
binary: overclockedmusicd | |
main: ./cmd/overclockedmusicd/ | |
env: | |
- CGO_ENABLED=0 | |
goos: | |
- aix | |
- darwin | |
- dragonfly | |
- freebsd | |
- illumos | |
- js | |
- linux | |
- netbsd | |
- openbsd | |
- plan9 | |
- solaris | |
- wasip1 | |
- windows | |
goarch: | |
- 386 | |
- amd64 | |
- arm | |
- arm64 | |
- loong64 | |
- mips | |
- mips64 | |
- mips64le | |
- mipsle | |
- ppc64 | |
- ppc64le | |
- riscv64 | |
- s390x | |
- wasm | |
goarm: | |
- 6 | |
- 7 | |
goamd64: | |
- v1 | |
- v2 | |
- v3 | |
- v4 | |
- id: ocmd-ios-with-sdk | |
binary: overclockedmusicd | |
main: ./cmd/overclockedmusicd/ | |
env: | |
- CGO_ENABLED=1 | |
goos: | |
- ios | |
goarch: | |
- arm64 | |
- id: ocmd-android-no-sdk | |
binary: overclockedmusicd | |
main: ./cmd/overclockedmusicd/ | |
env: | |
- CGO_ENABLED=0 | |
goos: | |
- android | |
goarch: | |
- arm64 | |
archives: | |
- id: ocmd | |
format: tar.gz | |
format_overrides: | |
- goos: windows | |
format: zip | |
checksum: | |
name_template: "checksums.txt" | |
snapshot: | |
version_template: "{{ .Tag }}-next" | |
changelog: | |
sort: asc | |
filters: | |
exclude: | |
- "^docs:" | |
- "^test:" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func startServer(ctx context.Context, sigChan chan os.Signal, dbURL string, addr string) { | |
routes := api.New(dbURL) | |
if err := routes.Init(keypair); err != nil { | |
log.Fatalf("Error while creating connection to the database!! %s", err) | |
} | |
mux := http.NewServeMux() | |
srv := reloadableserver.New(ctx, &http.Server{Addr: addr, Handler: mux}) | |
handleReload := createHandleReload(sigChan) | |
handleShutdown := createHandleShutdown(sigChan) | |
handleStatus := createHandleStatus(time.Now()) | |
mux.HandleFunc("GET /version", handleVersion) | |
mux.HandleFunc("GET /api/version", handleVersion) | |
mux.HandleFunc("GET /api/public/version", handleVersion) | |
mux.HandleFunc("GET /status", handleStatus) | |
mux.HandleFunc("GET /api/status", handleStatus) | |
mux.HandleFunc("GET /api/public/status", handleStatus) | |
m := mw.New(logPanics, routes.RequireEmployee) | |
mux.HandleFunc("GET /api/employee/slugs", m.Handle(routes.Slugs.All)) | |
mux.HandleFunc("POST /api/employee/slugs", m.Handle(routes.Slugs.AddMany)) | |
mux.HandleFunc("GET /api/employee/projects", m.Handle(routes.Everything)) | |
mux.HandleFunc("POST /api/employee/jobs", m.Handle(routes.Jobs.AddOne)) | |
mux.HandleFunc("PATCH /api/employee/jobs/{id}", m.Handle(routes.Jobs.PatchOne)) | |
adminM := m.Use(requireSudoer) | |
mux.HandleFunc("PUT /api/server", adminM.Handle(handleReload)) | |
mux.HandleFunc("DELETE /api/server", adminM.Handle(handleShutdown)) | |
log.Printf("Listening on %s", addr) | |
if err := srv.Run(); err != nil { | |
log.Fatalf("failed: %s", err) | |
return | |
} | |
reloadCount.Add(1) | |
log.Printf("graceful shutdown complete") | |
} | |
func logPanics(next http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
defer func() { | |
if _err := recover(); _err != nil { | |
err, ok := _err.(error) | |
if !ok { | |
err = fmt.Errorf("%v", _err) | |
} | |
api.InternalError(w, r, err) | |
return | |
} | |
}() | |
next.ServeHTTP(w, r) | |
} | |
} | |
func requireSudoer(next http.HandlerFunc) http.HandlerFunc { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
jws := r.Context().Value(api.ContextKeyJWS).(jwt.JWS) // allow to panic if key doesn't exist | |
path := r.URL.Path | |
if i := strings.Index(path, "?"); i != -1 { | |
path = path[:i] | |
} | |
isSuperAdmin := slices.Contains(jws.Claims.Roles, "sudo") | |
if !isSuperAdmin { | |
err := &api.JSONError{ | |
Status: http.StatusForbidden, | |
Code: "E_AUTHZ", | |
Description: "Please login as an administrator to access this resource.", | |
Details: fmt.Sprintf("%s %s requires application-level admin access", r.Method, path), | |
URI: "#authz-forbidden", | |
} | |
err.WriteTo(w) | |
return | |
} | |
next.ServeHTTP(w, r) | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mw | |
import ( | |
"net/http" | |
"slices" | |
) | |
// Middleware receives and returns and http.HandlerFunc | |
type Middleware func(http.HandlerFunc) http.HandlerFunc | |
// MiddlewareChain enables inline chaining | |
type MiddlewareChain struct { | |
middlewares []Middleware | |
} | |
// New creates a reusable MiddlewareChain with 0 or more middleware | |
func New(middlewares ...Middleware) MiddlewareChain { | |
return MiddlewareChain{middlewares: middlewares} | |
} | |
// Use appends additional middleware to the chain | |
func (c MiddlewareChain) Use(middlewares ...Middleware) MiddlewareChain { | |
newMiddlewares := make([]Middleware, len(c.middlewares), len(c.middlewares)+len(middlewares)) | |
copy(newMiddlewares, c.middlewares) | |
newMiddlewares = append(newMiddlewares, middlewares...) | |
return MiddlewareChain{middlewares: newMiddlewares} | |
} | |
// Handle composes middleware with the final handler | |
func (c MiddlewareChain) Handle(handler http.HandlerFunc) http.HandlerFunc { | |
if handler == nil { | |
panic("mw.New(...).Use(...).Handle(-->this<--) requires a handler") | |
} | |
middlewares := make([]Middleware, len(c.middlewares)) | |
copy(middlewares, c.middlewares) | |
slices.Reverse(middlewares) | |
// Apply middleware in forward order | |
result := handler | |
for _, m := range middlewares { | |
result = m(result) | |
} | |
return result | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- name: JobPatch :exec | |
UPDATE public.jobs | |
SET | |
label = COALESCE(sqlc.narg('label'), label), | |
customer = COALESCE(sqlc.narg('customer'), customer), | |
general_contractor = COALESCE(sqlc.narg('general_contractor'), general_contractor), | |
project_type = COALESCE(sqlc.narg('project_type'), project_type), | |
project_location = COALESCE(sqlc.narg('project_location'), project_location), | |
bid_date = COALESCE(sqlc.narg('bid_date')::TIMESTAMP, bid_date), | |
estimate = COALESCE(sqlc.narg('estimate')::DOUBLE PRECISION, estimate), | |
bid_type = COALESCE(sqlc.narg('bid_type'), bid_type), | |
status = COALESCE(sqlc.narg('status'), status), | |
updated_at = COALESCE(sqlc.narg('updated_at')::TIMESTAMP, CURRENT_TIMESTAMP), | |
closed_at = COALESCE(sqlc.narg('closed_at')::TIMESTAMP, closed_at), | |
notes = COALESCE(sqlc.narg('notes'), notes) | |
WHERE uuid = sqlc.arg('uuid'); | |
-- name: JobList :many | |
SELECT | |
uuid, | |
label, | |
customer, | |
general_contractor, | |
project_type, | |
project_location, | |
bid_date, | |
estimate, | |
bid_type, | |
status, | |
created_at, | |
updated_at, | |
closed_at, | |
notes | |
FROM public.jobs | |
WHERE CASE | |
WHEN sqlc.narg('uuids')::UUID[] IS NULL THEN TRUE | |
ELSE uuid = ANY(sqlc.narg('uuids')::UUID[]) | |
END | |
AND CASE | |
WHEN sqlc.narg('project_types')::TEXT[] IS NULL THEN TRUE | |
ELSE project_type = ANY(sqlc.narg('project_types')::TEXT[]) | |
END | |
AND CASE | |
WHEN sqlc.narg('bid_types')::TEXT[] IS NULL THEN TRUE | |
ELSE bid_type = ANY(sqlc.narg('bid_types')::TEXT[]) | |
END | |
AND CASE | |
WHEN sqlc.narg('project_locations')::TEXT[] IS NULL THEN TRUE | |
ELSE project_location = ANY(sqlc.narg('project_locations')::TEXT[]) | |
END; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/json" | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"strconv" | |
) | |
var ( | |
name = "overclockedmusicd" | |
version string | |
commit string | |
date string | |
defaultBind = "0.0.0.0" | |
defaultPort = 8080 | |
) | |
// workaround for `tinygo` ldflag replacement handling not allowing default values | |
// See <https://github.com/tinygo-org/tinygo/issues/2976> | |
func init() { | |
if len(version) == 0 { | |
version = "0.0.0-dev" | |
} | |
if len(date) == 0 { | |
date = "0001-01-01T00:00:00Z" | |
} | |
if len(commit) == 0 { | |
commit = "0000000" | |
} | |
} | |
func printVersion() { | |
fmt.Fprintf(os.Stderr, "%s <%s> %s (%s)\n", name, version, date, commit) | |
} | |
type Config struct { | |
APIVersion | |
Bind string | |
Port int | |
} | |
type APIVersion struct { | |
Version string `json:"version"` | |
Date string `json:"date"` | |
Commit string `json:"commit"` | |
} | |
func main() { | |
cfg := Config{} | |
cfg.Version = version | |
cfg.Date = date | |
cfg.Commit = commit | |
var needsHelp bool | |
if len(os.Args) > 1 { | |
switch os.Args[1] { | |
case "--help", "help": | |
printVersion() | |
needsHelp = true | |
case "-V", "--version", "version": | |
printVersion() | |
os.Exit(0) | |
default: | |
// nada | |
} | |
} | |
if len(os.Getenv("BIND_ADDRESS")) > 0 { | |
defaultBind = os.Getenv("BIND_ADDRESS") | |
} | |
{ | |
portStr := os.Getenv("PORT") | |
if len(portStr) > 0 { | |
port, err := strconv.Atoi(portStr) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "[warn] PORT=%s is not", os.Getenv("PORT")) | |
} | |
defaultPort = port | |
} | |
} | |
// var bind string | |
// var port int | |
flag.StringVar(&cfg.Bind, "bind", defaultBind, "which address to bind to") | |
flag.IntVar(&cfg.Port, "port", defaultPort, "which port to bind to") | |
// bindPtr := flag.String("bind", defaultBind, "which address to bind to") | |
// portPtr := flag.Int("port", defaultPort, "which port to bind to") | |
flag.Parse() | |
if needsHelp { | |
flag.Usage() | |
os.Exit(0) | |
} | |
mux := &http.ServeMux{} | |
cfg.SetupRoutes(mux) | |
addr := fmt.Sprintf("%s:%d", cfg.Bind, cfg.Port) | |
fmt.Fprintf(os.Stderr, "Listening on %s...\n", addr) | |
if err := http.ListenAndServe(addr, mux); err != nil { | |
log.Fatal(err) | |
} | |
} | |
type JSONError struct { | |
Error string `json:"error"` | |
Code string `json:"code"` | |
Details []string `json:"details"` | |
} | |
type userkey struct{} | |
var UserKey userkey | |
func (c Config) SetupRoutes(mux *http.ServeMux) { | |
mux.HandleFunc("GET /version", c.RequireAuth(func(w http.ResponseWriter, r *http.Request) { | |
var user string | |
userVal, ok := r.Context().Value(UserKey).(string) | |
if ok { | |
user = userVal | |
} | |
w.Header().Set("Content-Type", "application/json") | |
w.Header().Set("X-User", user) | |
// _, _ = fmt.Fprintf(w, `{"version":%q,"date":%q,"commit":%q}`+"\n", version, date, commit) | |
enc := json.NewEncoder(w) | |
_ = enc.Encode(c.APIVersion) | |
_, _ = w.Write([]byte("\n")) | |
})) | |
} | |
func (c Config) RequireAuth(next http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
user, _, ok := r.BasicAuth() | |
if !ok { | |
_ = json.NewEncoder(w).Encode(JSONError{ | |
"no auth details given", | |
"E_NO_BASIC", | |
[]string{"Authorization: Basic <base64(user:pass)> must be provided"}, | |
}) | |
return | |
} | |
ctx := context.WithValue(r.Context(), UserKey, user) | |
r = r.WithContext(ctx) | |
next.ServeHTTP(w, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment