Skip to content

Commit

Permalink
feat: add HTTP_ADDR env var
Browse files Browse the repository at this point in the history
Allow changing the bind address
  • Loading branch information
zimbatm committed Jul 28, 2024
1 parent 6a8a267 commit 730ae74
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ Inside the provided nix shell run:

This will create a small local server with live reload that emulates now.sh.

Currently, the default port is 8383. You can change it by setting the `PORT` environment variable.
Currently, the default port is 8383. You can change it by setting the `PORT`
environment variable, or `HTTP_ADDR` to also change the bind address.

## Usage

Expand All @@ -45,6 +46,7 @@ You can use the following environment variables to configure nar-serve:
| Name | Default value | Description |
|:-- |:-- |:-- |
| `PORT` | `8383` | Port number on which nar-service listens |
| `HTTP_ADDR` | `:$PORT` | HTTP address to bind the server to. When set, takes precedence over $PORT. |
| `NAR_CACHE_URL` | `https://cache.nixos.org` | The URL of the Nix store from which NARs are fetched |

## Contributing
Expand Down
23 changes: 18 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,21 @@ func healthzHandler(w http.ResponseWriter, r *http.Request) {
}

func main() {
var (
port = getEnv("PORT", "8383")
addr = getEnv("HTTP_ADDR", "")
)

if addr == "" {
addr = ":" + port
}

mux := http.NewServeMux()
mux.HandleFunc("/", indexHandler)
mux.HandleFunc("/healthz", healthzHandler)
mux.HandleFunc("/robots.txt", robotsHandler)
mux.HandleFunc(unpack.MountPath, unpack.Handler)

addr := ":8383"
if port := os.Getenv("PORT"); port != "" {
addr = ":" + port
}

// Includes some default middlewares
// Serve static files from ./public
n := negroni.New(
Expand All @@ -51,3 +55,12 @@ func main() {
n.UseHandler(mux)
n.Run(addr)
}

func getEnv(name, def string) string {
value := os.Getenv(name)
if value == "" {
return def
}
return value
}

0 comments on commit 730ae74

Please sign in to comment.