One weather contract for Go and PHP: checking data across the language boundary

Zero, null, large identifiers and duplicate keys: an independent contract, Go writer, PHP reader and an exact plan for a real cross-language run.

A conceptual illustration of different environments agreeing on the same data meaning.
A conceptual illustration of different environments agreeing on the same data meaning.

A weather importer can calculate temperature correctly while the website reads the result incorrectly. This does not require a complicated meteorological model defect. Converting an unavailable value to zero, rounding a revision identifier, or interpreting a new unit as an old one is enough. JSON delivers every character, yet the meaning has already changed between the two programs.

In this laboratory I define a small independent contract, prepare a Go writer and a PHP reader, and specify the experiment that would establish their compatibility. Both implementations use invented data. There is no weather provider request and no reproduction of a production schema.

The readiness boundary matters: the code and reference files are prepared, but Go, PHP and the cross-language passage have not been executed in this environment. The availability check did not establish the required runtimes. What follows is therefore a contract and a reproducible verification task, rather than a successfully completed integration. That distinction needs to remain visible when an article includes code.

Meaning comes before serialization

The teaching document contains one location, one source revision and two time points. The first temperature is zero; the second is unknown. Wind speed is known at both points. That is enough to examine several dangerous type transitions without a large collection of fields.

{
  "schema_version": 1,
  "location_id": "demo-kyiv",
  "source_revision": "9007199254740993",
  "issued_at": 1800000000,
  "units": {"temperature": "celsius", "wind_speed": "m/s"},
  "points": [
    {"at": 1800000000, "temperature": 0, "wind_speed": 1.5},
    {"at": 1800003600, "temperature": null, "wind_speed": 2}
  ]
}

The timestamps are synthetic inputs, not the time of the experiment. issued_at means the creation time of this teaching document. It does not establish when a provider initialized its model, whether the document was published, or whether the forecast remains fresh. Those conclusions require other rules, which this example deliberately does not assign to one field.

Part Rule in our contract
Version Exactly 1, written as a JSON integer
Revision A string of 1–32 decimal digits, with no leading zero
Time Whole UTC seconds; no milliseconds or fractional notation
Temperature Required key; a finite number or explicit null
Wind Required finite nonnegative number
Points From 1 to 24; strictly increasing times within the next 86400 seconds
Shape Known keys only, exact name casing, no duplicates

These are local choices for the exercise. Another contract could represent unavailable temperature by omitting a key. Here the key is required, so omission means a damaged structure while null is a supported state. Both sides must accept that choice before agreeing on the file format.

Where identical JSON invites different assumptions

The revision 9007199254740993 deliberately exceeds the range in which binary64 represents every integer exactly. RFC 8259 describes an interoperable integer range ending at 2^53−1 for this case. That is not a limitation of every Go or PHP integer type; the problem arises when an intermediate path uses floating point. An opaque identity does not need arithmetic, so this contract requires a string. Source: RFC 8259, numbers.

Converting any received number to a string after decoding does not solve the problem: the original digits may already have changed. The reader must reject a numeric revision. It also neither pads the revision with zeros nor compares it as a decimal counter. Identity is preserved literally.

Physical quantities follow a different rule. Temperatures 0 and 0.0 mean the same value, while null equals neither. For control fields I choose a stricter grammar: 1.0 or 18e8 is not an allowed spelling of a version or timestamp, even when its mathematical value is integral. This is an explicit exercise requirement, not a universal JSON property.

Units are part of validation too. The reader accepts only celsius and m/s; it does not guess conversions from kelvin or kilometres per hour. However, a correct unit label does not prove the number correct: a value wrongly labelled Celsius could pass structural validation. Contract validation constrains representation; checking provenance and normalization remains a separate task.

A decoder must retain distinctions until validation

In Go I use encoding/json, retaining numeric tokens with UseNumber, then check shape, types and relationships separately. The documentation describes decoding defaults and the option to preserve a number as json.Number. That matters when an integer timestamp spelling must be distinguished from exponential notation. Source: encoding/json.

Blindly populating a struct is insufficient for this agreement. We need to know whether a key appeared at all, whether its name has the exact casing, and whether an extra member was supplied. Size-bounded tokens are therefore read first; the typed document is constructed after validation. Input is limited to 8192 bytes, with a teaching depth limit of 16 levels. These are example bounds, not a recommendation for every weather payload.

In PHP, json_decode uses exceptions and preserves objects as objects. Its official description explains shape, depth and error handling parameters. After syntax decoding, the code checks stdClass, the points array, property presence and exact types; in particular, property_exists is needed where null is allowed. Source: PHP json_decode.

Duplicate keys are a separate trap. RFC 8259 recommends unique names because readers disagree when names repeat. Our contract makes that requirement mandatory. A duplicate is detected before the decoded values are used, including when the second name uses an escape sequence: schema_version and schema_versi\u006fn are the same name. Source: RFC 8259, objects.

The PHP duplicate check does not replace the JSON parser: the standard function checks syntax first. A small additional walk only tracks already valid keys inside nested objects. That walk also needs execution and testing with real PHP; reading its source does not establish its behaviour.

The reference file must be independent of the writer

If the same serializer creates both a test's expected result and the result under examination, both can repeat the same mistake. Consequently, fixtures/valid.json is a literal reference document. The Go writer must reproduce its bytes, including the final newline. This is a narrow stability check for one particular writer.

PHP needs a different check: the recovered meaning must match the reference document. Key order and whitespace do not affect that equality. PHP may emit 0.0 where Go emitted 0; that is acceptable for temperature. A second positive file deliberately changes key order and physical-number spelling. After another strict read, every value is compared, not just the point count.

There are also 20 prepared negative files. They cover an unknown version, a numeric revision and null instead of a string, forbidden timestamp spelling, wrong units, extra and missing keys, a string temperature, infinity after numeric conversion, negative wind, empty or incorrectly ordered points, duplicate keys and a second JSON document after the first. These are prepared inputs, not twenty successfully executed tests.

Semantic equality does not imply matching hashes for two JSON files. If the document is later signed, or its bytes become part of snapshot identity, a separate canonical encoding rule is needed. The current reader cannot declare different byte sequences equal for that signature merely because the temperatures match. In this laboratory, exact byte equality checks one reference output; semantic equality checks the transfer of values between languages.

Rejection must also be complete. The reader forms its normalized output only after validating every point. If the second point is damaged, it must not emit the first as though it were a complete forecast. Such partial acceptance would change the contract's promise without the consumer knowing.

Running a real cross-language passage

The laboratory must run in an isolated directory with a real Go toolchain and a 64-bit PHP CLI. An executable named go is insufficient by itself: tool versions are checked first. run_lab.py only orchestrates external processes; it neither reads data in place of PHP nor emulates a Go compiler.

The check requires running the Go writer, the PHP reader and the result comparison in sequence.

In that experiment, both readers must reject every negative file, and PHP must accept both positive files. Preserve actual versions, stdout, stderr and exit codes. One serializer returning zero does not replace evidence from the second process.

This stage remains unexecuted in the prepared package: a real Go toolchain was not confirmed, and PHP CLI is absent. Even PHP syntax has not been marked as checked with php -l. The next executor must start there, run the tests, fix any differences and repeat the entire bounded passage. Examining JSON with another language can help inspect fixtures, but it does not establish Go–PHP compatibility.

An agreement changes the version, not an extra key

The document's closed shape deliberately rejects unknown fields. That gives a clear refusal but requires coordinated evolution. Adding pressure to the writer does not become compatible automatically because JSON allows another key–value pair. Semantics, units, the missing state and reader behaviour are defined first; the version and reference documents are then updated.

A broader contract would also need provenance for each field, time intervals, partial coverage, source revisions and a separate freshness rule. Adding them decoratively would not help this exercise: every extension creates new assertions that both languages must validate consistently.

The completion criterion is specific: Go created the document, PHP read it without losing zero, unknown values, units or identity, and both readers rejected the dangerous inputs consistently. Until real processes demonstrate that, we have a prepared contract and an exact verification procedure. After a successful run, we will have evidence of compatibility for this particular version and this bounded collection of scenarios.

  1. Vendors & Packages A package’s public contract extends beyond method signatures
  2. API Testing an API without a live database: what a fixture proves and what it does not
  3. Weather An optimization that failed validation: evaluating speed across the whole path
  4. Weather Multiple weather providers: a shared contract without losing important differences

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article