Configuration

The directory app/ contains the configuration of gox-server.

Your point of entry is app/config.goxwhere the function SetGoxConfig() builds an instance of server.ConfigThis structure brings together the configuration of Dev, HTTP, rate limiting, sessions, static files, routes, WebSocket, cluster and server life cycle.

text
my-project/
└── app/
    ├── config.gox
    ├── http.gox
    ├── ratelimit.gox
    ├── routes.gox
    ├── session.gox
    ├── static.gox
    ├── websocket.gox
    ├── startup.gox
    └── shutdown.gox

Separate files allow each area to be kept in its own module. config.gox It matters and composes the final configuration used by the runtime.


Entry point

The file app/config.gox use the module app and must declare the function SetGoxConfig with this signature:

gox
func SetGoxConfig() server.Config
gox
module app

import (
    "github.com/gox-lang/gox/server"
    "http.gox"
    "ratelimit.gox"
    "routes.gox"
    "session.gox"
    "shutdown.gox"
    "startup.gox"
    "static.gox"
    "websocket.gox"
)

func SetGoxConfig() server.Config {
    return server.Config{
        ProjectName: "hello",

        Dev: server.DevConfig{
            Enabled: true,
            Logs: server.DevLogsConfig{
                Static:    false,
                GoxFile:   true,
                Trace:     false,
                TraceDeep: false,
            },
        },

        Cluster: nil,

        HTTP:      http.Config,
        RateLimit: ratelimit.Config,
        Session:   session.Config,
        Static:    static.Config,
        Routes:    routes.Config,
        WebSocket: websocket.Config,

        OnStartServer: startup.OnStartServer,
        OnStopServer:  shutdown.OnStopServer,
    }
}

SetGoxConfig() is the input module configuration export. Your name and type of return are part of the contract you use gox-server to locate and load the configuration.

The compiler requires that:

  • The function is called exactly SetGoxConfig.
  • There is no more than one type export server.Config in the input module.
  • The function does not receive parameters.
  • The value returned is server.Config.

If the file cannot be compiled or the symbol does not have the expected signature, the runtime cannot load that version of the configuration.


Main configuration

server.Config Its public fields connect each subsystem with the runtime:

FieldTypeLiability
ProjectNamestringIdentify the project.
Devserver.DevConfigConfigure Dev and his logs.
Clusterserver.ClusterAdapterConnect a distributed adapter.
HTTPserver.HTTPConfigConfigure the list and HTTP processing.
RateLimitserver.RateLimitConfigIt defines the request limitation policies.
Sessionserver.SessionConfigConfigure the storage and life cycle of the sessions.
Staticserver.StaticConfigConfigure the static file service.
Routesserver.RoutesConfigDeclares public routes to internal destinations.
WebSocketserver.WebSocketConfigConfigure WebSocket transport.
OnStartServerfunc() errorRun the server initialization.
OnStopServerfunc() errorExecuts the release of resources.

Subordinated structures retain independent types. This allows you to validate your fields during the compilation and replace a complete configuration without using options maps or dynamic values.


ProjectName

Tipo:string

ProjectName identifies the application to the runtime.

gox
ProjectName: "hello",

gox createproject use the project name to generate this value. gox.Server.ProjectName():

gox
projectName := gox.Server.ProjectName()

The name is also part of the identity used when opening the session storage and a cluster adapter. All instances belonging to the same distributed deployment must use the same ProjectName.

Changing it makes the runtime treat the application as another project to the resources that use that identity.


Module composition

The structure created by GOX declares a variable Config within each technical module:

gox
module http

import "github.com/gox-lang/gox/server"

var Config = server.HTTPConfig{
    Host: "localhost",
    Port: 3000,
}

app/config.gox import the file and assign its value to the relevant field:

gox
HTTP: http.Config,

The identifier Config within http.gox, session.gox or any other module is an organizational decision, not a special runtime requirement. The configuration can also be built directly:

gox
func SetGoxConfig() server.Config {
    return server.Config{
        ProjectName: "hello",
        Cluster:     nil,
        HTTP: server.HTTPConfig{
            Host: "localhost",
            Port: 3000,
        },
    }
}

The technical requirement is that SetGoxConfig() return a valid instance of server.Config. Separate the areas into modules makes it easier to read and avoid concentrating all the options in a single file.


Configuration areas

Dev

Dev controls its mode of execution and the categories of logs issued by gox-server.

gox
Dev: server.DevConfig{
    Enabled: true,
    Logs: server.DevLogsConfig{
        Static:    false,
        GoxFile:   true,
        Trace:     false,
        TraceDeep: false,
    },
},

See Dev to know Enabled, Static, GoxFile, Trace and TraceDeep.

HTTP

HTTP defines the direction of the list, the permitted methods, the compression of responses and the resolution of the client's IP behind proxies.

gox
HTTP: http.Config,

See HTTP to know server.HTTPConfig and their subordinate structures.

Rate limiting

RateLimit contains the rules that limit requests according to criteria such as IP, session, route, method or URL.

gox
RateLimit: ratelimit.Config,

See Rate limit to know the strategies, filters and patterns available.

Sessions

Session Configure the life time and handlers executed when creating or expiring a session. Local or distributed storage is selected by Cluster.

gox
Session: session.Config,

See Sessions to know server.SessionConfig.

Static files

Static controls the public directory, partial responses, streaming, headers and file compression.

gox
Static: static.Config,

See Static files to know server.StaticConfig.

Routes

Routes links public patterns to Pages, Actions or other internal destinations of the application.

gox
Routes: routes.Config,

See Routes to know the exact routes, parameters, optional segments, wildcard and alternatives.

WebSocket

WebSocket defines the limits and times of the handshake, messages, writing, Heartbeat, queues, buffers and compression.

gox
WebSocket: websocket.Config,

See WebSocket to know server.WebSocketConfig.

Cluster

Cluster receives an implementation of server.ClusterAdapter.

gox
Cluster: nil,

nil is the zero value of the interface and maintains the distributed runtime disable. In this state, the instance manages local sessions, sockets, groups and channels.

To execute several instances of gox-server, assigns a compatible adapter:

gox
Cluster: adapter,

See Cluster to know the configuration contract and shared storage.

Lifecycle

OnStartServer and OnStopServer receive optional functions with the signature func() error:

gox
OnStartServer: startup.OnStartServer,
OnStopServer:  shutdown.OnStopServer,
gox
module startup

func OnStartServer() error {
    return nil
}

These functions allow the opening and closing of resources managed by the application. Lifecycle to know your execution order and the treatment of errors.


Zero values and default values

The fields of server.Config use go's normal zero values. Runtime interprets some of those values as a request to apply a fallback.

For example:

FieldZero valueRuntime behaviour
HTTP.Host""Use localhost.
HTTP.Port0Use the port 3000.
Session.TTL0It uses a 3-hour TTL.
Static.Path""Use the directory public.
Static.StreamMinFileSize0It uses 512 KiB.
ClusternilIt keeps the cluster disabled.
OnStartServernilHe doesn't run a start handler.
OnStopServernilHe doesn't run a closing handler.

The zero value and the value generated by gox createproject The scaffold declares explicit options to show the initial project configuration, while the runtime retains fallbacks for omitted configurations.

Each technical page documents the zero values, fallbacks and validations of its own structure.


Reloading

The files in the directory app/ they are involved in the automatic recharge of GOX.

When one of these files changes, GOX recompiles app/config.gox, builds a new state of the runtime and replaces areas that can be updated without stopping the process. If the new configuration does not compile, cannot be validated or fails to open its resources, the previous version remains active.

Change the host, ports or TLS configuration automatically reboot GOX. Other options apply to subsequent requests without reboot. Update manual certificate files and renew automatic certificates does not require reboot. HTTP Recharge for details, including proxy policy and DNS suppliers.

Technical pages include a section Reloading which indicates which fields are applied immediately, which only affect resources created after the change and which require reinitiation of the instance.


Integration with Go

The configuration is built by structures, interfaces, functions, slices, maps and values of time.Duration It can be divided into modules and reuse auxiliary functions with the same type system that uses the rest of the application.

SetGoxConfig() The compiler validates the names of the fields, the assigned types and the signatures of the handlers before the runtime uses the configuration, maintaining a family experience for any developer with go experience.


Best practices

  • Preservation app/config.gox as the point of composition of the configuration.
  • Separate each subsystem into a module focused on a single responsibility.
  • Keep ProjectName stable between deployments of the same project.
  • Use the same ProjectName in all the instances of a cluster.
  • Preservation Cluster in nil when the application is executed in a single instance.
  • Check the zero value behavior before omitting a field.
  • Keep the secrets out of the configuration files.
  • It spreads the errors produced during initialization and closure.
  • Avoid performing expensive work directly within SetGoxConfig().

See also

Next step

Continue with Dev to configure Dev and the logs issued by gox-server.

Dev