-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserve_dev.go
More file actions
72 lines (62 loc) · 1.74 KB
/
serve_dev.go
File metadata and controls
72 lines (62 loc) · 1.74 KB
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
//go:build shiftapidev
package shiftapi
import (
"encoding/json"
"log"
"net/http"
"os"
)
const devMode = true
// ListenAndServe starts the HTTP server on the given address.
//
// In production builds this is a direct call to [http.ListenAndServe] with
// zero additional overhead.
//
// When built with -tags shiftapidev (used automatically by the Vite plugin),
// the following environment variables are supported:
// - SHIFTAPI_EXPORT_SPEC=<path>: write the OpenAPI spec to the given file
// and exit without starting the server.
// - SHIFTAPI_PORT=<port>: override the port in addr, allowing the Vite
// plugin to automatically assign a free port.
func ListenAndServe(addr string, api *API) error {
log.Println("shiftapi: running in dev mode (shiftapidev build tag)")
if specPath := os.Getenv("SHIFTAPI_EXPORT_SPEC"); specPath != "" {
if err := exportSpec(api, specPath); err != nil {
return err
}
if asyncPath := os.Getenv("SHIFTAPI_EXPORT_ASYNCAPI"); asyncPath != "" {
if err := exportAsyncSpec(api, asyncPath); err != nil {
return err
}
}
os.Exit(0)
}
if port := os.Getenv("SHIFTAPI_PORT"); port != "" {
addr = ":" + port
log.Printf("shiftapi: listening on %s (via SHIFTAPI_PORT)", addr)
}
return http.ListenAndServe(addr, api)
}
func exportSpec(api *API, path string) error {
return exportJSON(api.spec, path)
}
func exportAsyncSpec(api *API, path string) error {
return exportJSON(api.asyncSpec, path)
}
func exportJSON(v any, path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
if err := enc.Encode(v); err != nil {
_ = f.Close()
return err
}
if err := f.Sync(); err != nil {
_ = f.Close()
return err
}
return f.Close()
}