| 1 |
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
// Package openapi_schemas contains the OpenAPI 3.0 and 3.1 schemas that are loaded from libopenapi, or our own |
| 5 |
// fork of the official OpenAPI repo specifications. Using an MD5 hash, we can compare the local version against |
| 6 |
// the remote version and determine if they differ, if they do - load the remote version. |
| 7 |
package openapi_schemas |
| 8 |
|
| 9 |
import ( |
| 10 |
"crypto/md5" |
| 11 |
"encoding/hex" |
| 12 |
"io" |
| 13 |
"net/http" |
| 14 |
|
| 15 |
_ "embed" |
| 16 |
) |
| 17 |
|
| 18 |
var schema30, schema31 string |
| 19 |
|
| 20 |
// LoadSchema3_0 loads the latest OpenAPI 3.0 specification. The latest version is fetched from the OpenAPI repo. |
| 21 |
// and if there is no change in the schema, the local version is returned, otherwise the remote version is returned. |
| 22 |
func LoadSchema3_0(schema string) string { |
| 23 |
if schema30 != "" { |
| 24 |
return schema30 |
| 25 |
} |
| 26 |
remoteSpec := "https://raw.githubusercontent.com/pb33f/openapi-specification/main/schemas/v3.0/schema.json" |
| 27 |
schema30 = extractSchema(remoteSpec, schema) |
| 28 |
return schema30 |
| 29 |
} |
| 30 |
|
| 31 |
// LoadSchema3_1 loads the latest OpenAPI 3.1 specification. The latest version is fetched from the OpenAPI repo. |
| 32 |
// and if there is no change in the schema, the local version is returned, otherwise the remote version is returned. |
| 33 |
func LoadSchema3_1(schema string) string { |
| 34 |
if schema31 != "" { |
| 35 |
return schema31 |
| 36 |
} |
| 37 |
remoteSpec := "https://raw.githubusercontent.com/pb33f/openapi-specification/main/schemas/v3.1/schema.json" |
| 38 |
schema31 = extractSchema(remoteSpec, schema) |
| 39 |
return schema31 |
| 40 |
} |
| 41 |
|
| 42 |
func getFile(url string) ([]byte, error) { |
| 43 |
resp, err := http.Get(url) |
| 44 |
if err != nil { |
| 45 |
return nil, err |
| 46 |
} |
| 47 |
return io.ReadAll(resp.Body) |
| 48 |
} |
| 49 |
|
| 50 |
func extractSchema(url string, local string) string { |
| 51 |
// check the local version against the latest version held in our repo. |
| 52 |
remoteVersion, err := getFile(url) |
| 53 |
if err != nil { |
| 54 |
return local |
| 55 |
} |
| 56 |
remoteHash := md5.Sum(remoteVersion) |
| 57 |
remoteMD5 := hex.EncodeToString(remoteHash[:]) |
| 58 |
|
| 59 |
localHash := md5.Sum([]byte(local)) |
| 60 |
localMD5 := hex.EncodeToString(localHash[:]) |
| 61 |
|
| 62 |
if remoteMD5 != localMD5 { |
| 63 |
return string(remoteVersion) |
| 64 |
} |
| 65 |
return local |
| 66 |
} |