### Register and Use Custom FHIRPath Functions in Go Source: https://context7.com/verily-src/fhirpath-go/llms.txt This Go code demonstrates how to register and use custom functions within the fhirpath-go library. It shows the definition of a 'reverse' function to reverse strings and a 'validate' function to check for a pattern within strings. The example includes compiling FHIRPath expressions with these custom functions and evaluating them against a sample FHIR Patient resource. ```go package main import ( "fmt" "log" "strings" "github.com/verily-src/fhirpath-go/fhirpath" "github.com/verily-src/fhirpath-go/fhirpath/compopts" "github.com/verily-src/fhirpath-go/fhirpath/system" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" dtpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/datatypes_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" ) func main() { // Define a custom function that transforms input customReverse := func(input system.Collection, args ...any) (system.Collection, error) { result := system.Collection{} for _, item := range input { if str, ok := item.(system.String); ok { reversed := reverseString(string(str)) result = append(result, system.String(reversed)) } else if fhirStr, ok := item.(*dtpb.String); ok { reversed := reverseString(fhirStr.Value) result = append(result, system.String(reversed)) } } return result, nil } // Define a custom validation function customValidate := func(input system.Collection, args ...any) (system.Collection, error) { if len(args) == 0 { return system.Collection{system.Boolean(false)}, nil } pattern, ok := args[0].(system.String) if !ok { return system.Collection{system.Boolean(false)}, nil } for _, item := range input { if str, ok := item.(system.String); ok { if strings.Contains(string(str), string(pattern)) { return system.Collection{system.Boolean(true)}, nil } } } return system.Collection{system.Boolean(false)}, nil } patient := &ppb.Patient{ Name: []*dtpb.HumanName{ { Given: []*dtpb.String{fhir.String("Alice")}, Family: fhir.String("Johnson"), }, }, } // Compile with custom function expr, err := fhirpath.Compile( "Patient.name.given.reverse()", compopts.AddFunction("reverse", customReverse), ) if err != nil { log.Fatalf("Failed to compile: %v", err) } result, err := expr.Evaluate([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Reversed name: %v\n", result) // Output: Reversed name: [ecilA] // Use custom validation function with arguments validateExpr, err := fhirpath.Compile( "Patient.name.given.validate('lic')", compopts.AddFunction("validate", customValidate), ) if err != nil { log.Fatalf("Failed to compile: %v", err) } isValid, err := validateExpr.EvaluateAsBool([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Name contains 'lic': %v\n", isValid) // Output: Name contains 'lic': true } func reverseString(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } ``` -------------------------------- ### Parse and Convert FHIRPath System Types in Go Source: https://context7.com/verily-src/fhirpath-go/llms.txt Demonstrates parsing various FHIRPath system types like Date, DateTime, and Quantity directly using the `system` package. It also shows how to convert FHIR proto types (e.g., String) into FHIRPath system types. ```go package main import ( "fmt" "log" "time" "github.com/verily-src/fhirpath-go/fhirpath" "github.com/verily-src/fhirpath-go/fhirpath/evalopts" "github.com/verily-src/fhirpath-go/fhirpath/system" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" dtpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/datatypes_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" "github.com/shopspring/decimal" ) func main() { // Work with system types directly date, err := system.ParseDate("2024-12-25") if err != nil { log.Fatalf("Failed to parse date: %v", err) } fmt.Printf("Parsed date: %v\n", date) // Output: Parsed date: 2024-12-25 dateTime, err := system.ParseDateTime("2024-12-25T10:30:00Z") if err != nil { log.Fatalf("Failed to parse datetime: %v", err) } fmt.Printf("Parsed datetime: %v\n", dateTime) // Output: Parsed datetime: 2024-12-25T10:30:00Z quantity, err := system.ParseQuantity("75.5", "kg") if err != nil { log.Fatalf("Failed to parse quantity: %v", err) } fmt.Printf("Parsed quantity: %v %s\n", quantity.Decimal, quantity.Unit()) // Output: Parsed quantity: 75.5 kg // Convert FHIR proto types to System types fhirString := fhir.String("Hello") systemString, err := system.From(fhirString) if err != nil { log.Fatalf("Failed to convert: %v", err) } fmt.Printf("System string: %v (type: %s)\n", systemString, systemString.Name()) // Output: System string: Hello (type: String) // Work with literals in FHIRPath patient := &ppb.Patient{ BirthDate: fhir.MustParseDate("2000-01-01"), } // Date arithmetic with quantities dateArithExpr := fhirpath.MustCompile("@2024-01-01 + 30 'days'") result, err := dateArithExpr.Evaluate([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Date + 30 days: %v\n", result) // Output: Date + 30 days: [2024-01-31] // Decimal arithmetic decimalExpr := fhirpath.MustCompile("1.5 + 2.7") decResult, err := decimalExpr.Evaluate([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } if len(decResult) > 0 { if dec, ok := decResult[0].(system.Decimal); ok { fmt.Printf("Decimal result: %v\n", decimal.Decimal(dec)) // Output: Decimal result: 4.2 } } // Override time for now() function testTime := time.Date(2024, 6, 15, 12, 0, 0, 0, time.UTC) nowExpr := fhirpath.MustCompile("now()") nowResult, err := nowExpr.Evaluate( []fhirpath.Resource{patient}, evalopts.OverrideTime(testTime), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Overridden now(): %v\n", nowResult) // Output: Overridden now(): [2024-06-15T12:00:00Z] // Type checking with is operator typeCheckExpr := fhirpath.MustCompile("1 is Integer") isInteger, err := typeCheckExpr.EvaluateAsBool([]fhirpath.Resource{}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("1 is Integer: %v\n", isInteger) // Output: 1 is Integer: true // Collection operations collection := system.Collection{ system.String("a"), system.String("b"), system.String("c"), } containsValue := collection.Contains(system.String("b")) fmt.Printf("Collection contains 'b': %v\n", containsValue) // Output: Collection contains 'b': true } ``` -------------------------------- ### Go: Apply FHIR Resource Patch Operations (Add, Replace, Delete, Insert) Source: https://context7.com/verily-src/fhirpath-go/llms.txt Demonstrates applying patch operations to a FHIR Patient resource using the fhirpath-go library. It covers adding a new name, replacing the active status, deleting a name entry, and inserting a name at a specific index. Requires the fhirpath-go and Google FHIR Go proto libraries. ```go package main import ( "fmt" "log" "github.com/verily-src/fhirpath-go/fhirpath/patch" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" dtpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/datatypes_go_proto" cpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/codes_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" ) func main() { // Create a Patient resource patient := &ppb.Patient{ Id: fhir.ID("patient-123"), Active: fhir.Boolean(true), Name: []*dtpb.HumanName{ { Use: &dtpb.HumanName_UseCode{Value: cpb.NameUseCode_OFFICIAL}, Given: []*dtpb.String{fhir.String("John")}, Family: fhir.String("Smith"), }, }, } // Add operation: Add a new name addExpr, err := patch.Compile("Patient.name") if err != nil { log.Fatalf("Failed to compile patch: %v", err) } newName := &dtpb.HumanName{ Use: &dtpb.HumanName_UseCode{Value: cpb.NameUseCode_NICKNAME}, Given: []*dtpb.String{fhir.String("Johnny")}, Family: fhir.String("Smith"), } err = addExpr.Add(patient, "name", newName, nil) if err != nil { log.Fatalf("Failed to add: %v", err) } fmt.Printf("After add: %d names\n", len(patient.Name)) // Output: After add: 2 names // Replace operation: Update existing field replaceExpr, err := patch.Compile("Patient.active") if err != nil { log.Fatalf("Failed to compile patch: %v", err) } err = replaceExpr.Replace(patient, fhir.Boolean(false), nil) if err != nil { log.Fatalf("Failed to replace: %v", err) } fmt.Printf("After replace: active = %v\n", patient.Active.Value) // Output: After replace: active = false // Delete operation: Remove a field deleteExpr, err := patch.Compile("Patient.name[1]") if err != nil { log.Fatalf("Failed to compile patch: %v", err) } err = deleteExpr.Delete(patient, nil) if err != nil { log.Fatalf("Failed to delete: %v", err) } fmt.Printf("After delete: %d names\n", len(patient.Name)) // Output: After delete: 1 names // Insert operation: Insert at specific index insertExpr, err := patch.Compile("Patient.name") if err != nil { log.Fatalf("Failed to compile patch: %v", err) } anotherName := &dtpb.HumanName{ Given: []*dtpb.String{fhir.String("J")}, Family: fhir.String("Smith"), } err = insertExpr.Insert(patient, anotherName, 0, nil) if err != nil { log.Fatalf("Failed to insert: %v", err) } fmt.Printf("After insert: %d names, first given = %s\n", len(patient.Name), patient.Name[0].Given[0].Value) // Output: After insert: 2 names, first given = J } ``` -------------------------------- ### Evaluate Boolean and Comparison Expressions in Go Source: https://context7.com/verily-src/fhirpath-go/llms.txt This Go code demonstrates how to evaluate boolean conditions and perform comparisons using the fhirpath-go library. It covers checking patient status, age validation using date arithmetic, and comparing gender codes. Dependencies include the fhirpath-go library and FHIR protocol buffers. ```go package main import ( "fmt" "log" "github.com/verily-src/fhirpath-go/fhirpath" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" cpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/codes_go_proto" ) func main() { patient := &ppb.Patient{ Active: fhir.Boolean(true), BirthDate: fhir.MustParseDate("2000-03-22"), Gender: &ppb.Patient_GenderCode{ Value: cpb.AdministrativeGenderCode_FEMALE, }, } // Boolean evaluation: check if patient is active activeExpr := fhirpath.MustCompile("Patient.active = true") isActive, err := activeExpr.EvaluateAsBool([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Patient is active: %v\n", isActive) // Output: Patient is active: true // Date comparison: validate age ageExpr := fhirpath.MustCompile("Patient.birthDate + 23 'years' <= today()") isOldEnough, err := ageExpr.EvaluateAsBool([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Patient is 23 or older: %v\n", isOldEnough) // Output: Patient is 23 or older: true // Gender code comparison genderExpr := fhirpath.MustCompile("Patient.gender = 'female'") isFemale, err := genderExpr.EvaluateAsBool([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Patient gender is female: %v\n", isFemale) // Output: Patient gender is female: true } ``` -------------------------------- ### Resolve FHIR References with Bundle Resolver in Go Source: https://context7.com/verily-src/fhirpath-go/llms.txt This Go code snippet demonstrates resolving FHIR references within a Bundle. It creates a Patient and an Observation that references the Patient, packages them into a Bundle, and then uses the BundleResolver to evaluate FHIRPath expressions to retrieve related data. Dependencies include the fhirpath-go library and Google's FHIR proto definitions. The input is a FHIR Bundle and a FHIRPath expression, and the output is the resolved data from the referenced resource. ```go package main import ( "fmt" "log" "github.com/verily-src/fhirpath-go/fhirpath" "github.com/verily-src/fhirpath-go/fhirpath/evalopts" "github.com/verily-src/fhirpath-go/fhirpath/resolver" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" opb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/observation_go_proto" r4pb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/bundle_and_contained_resource_go_proto" dtpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/datatypes_go_proto" cpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/codes_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" "github.com/verily-src/fhirpath-go/internal/containedresource" ) func main() { // Create a Patient resource patient := &ppb.Patient{ Id: fhir.ID("patient-123"), Name: []*dtpb.HumanName{ { Given: []*dtpb.String{fhir.String("John")}, Family: fhir.String("Doe"), }, }, } // Create an Observation that references the Patient observation := &opb.Observation{ Id: fhir.ID("obs-456"), Status: &opb.Observation_StatusCode{ Value: cpb.ObservationStatusCode_FINAL, }, Subject: &dtpb.Reference{ Reference: &dtpb.Reference_PatientId{ PatientId: fhir.String("patient-123"), }, }, } // Create a Bundle containing both resources bundle := &r4pb.Bundle{ Type: &r4pb.Bundle_TypeCode{ Value: cpb.BundleTypeCode_COLLECTION, }, Entry: []*r4pb.Bundle_Entry{ { FullUrl: fhir.URI("http://example.com/Patient/patient-123"), Resource: containedresource.Wrap(patient), }, { FullUrl: fhir.URI("http://example.com/Observation/obs-456"), Resource: containedresource.Wrap(observation), }, }, } // Create a BundleResolver bundleResolver, err := resolver.NewBundleResolver(bundle) if err != nil { log.Fatalf("Failed to create resolver: %v", err) } // Compile expression that uses resolve() function expr := fhirpath.MustCompile("Observation.subject.resolve().name.family") // Evaluate with resolver result, err := expr.Evaluate( []fhirpath.Resource{observation}, evalopts.WithResolver(bundleResolver), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } if len(result) > 0 { if familyName, ok := result[0].(*dtpb.String); ok { fmt.Printf("Resolved patient family name: %s\n", familyName.Value) // Output: Resolved patient family name: Doe } } // Resolve with chained navigation chainedExpr := fhirpath.MustCompile("Observation.subject.resolve().ofType(Patient).name.given.first()") givenResult, err := chainedExpr.EvaluateAsString( []fhirpath.Resource{observation}, evalopts.WithResolver(bundleResolver), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Resolved given name: %s\n", givenResult) // Output: Resolved given name: John } ``` -------------------------------- ### Utilize FHIRPath Functions for Data Manipulation in Go Source: https://context7.com/verily-src/fhirpath-go/llms.txt This Go code illustrates the use of built-in FHIRPath functions provided by the fhirpath-go library. It covers filtering collections with `where()`, transforming data with `select()`, checking for existence with `exists()`, string manipulation with `upper()`, and substring checking with `contains()`. It requires the fhirpath-go library and FHIR protocol buffers. ```go package main import ( "fmt" "log" "github.com/verily-src/fhirpath-go/fhirpath" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" dtpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/datatypes_go_proto" cpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/codes_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" ) func main() { patient := &ppb.Patient{ Name: []*dtpb.HumanName{ { Use: &dtpb.HumanName_UseCode{Value: cpb.NameUseCode_OFFICIAL}, Given: []*dtpb.String{fhir.String("John")}, Family: fhir.String("Smith"), }, { Use: &dtpb.HumanName_UseCode{Value: cpb.NameUseCode_NICKNAME}, Given: []*dtpb.String{fhir.String("Johnny")}, Family: fhir.String("Smith"), }, }, } // where() - Filter collection by condition whereExpr := fhirpath.MustCompile("Patient.name.where(use = 'official')") officialNames, err := whereExpr.Evaluate([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed: %v", err) } fmt.Printf("Found %d official name(s)\n", len(officialNames)) // Output: Found 1 official name(s) // select() - Project collection to new values selectExpr := fhirpath.MustCompile("Patient.name.select(given.first() + ' ' + family)") fullNames, err := selectExpr.Evaluate([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed: %v", err) } fmt.Printf("Full names: %v\n", fullNames) // Output: Full names: [John Smith Johnny Smith] // exists() - Check if any element matches condition existsExpr := fhirpath.MustCompile("Patient.name.exists(use = 'nickname')") hasNickname, err := existsExpr.EvaluateAsBool([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed: %v", err) } fmt.Printf("Has nickname: %v\n", hasNickname) // Output: Has nickname: true // String manipulation functions upperExpr := fhirpath.MustCompile("Patient.name[0].family.upper()") upperFamily, err := upperExpr.EvaluateAsString([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed: %v", err) } fmt.Printf("Uppercase family name: %s\n", upperFamily) // Output: Uppercase family name: SMITH // contains() - Check substring containsExpr := fhirpath.MustCompile("Patient.name[0].given.contains('oh')") containsSubstring, err := containsExpr.EvaluateAsBool([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed: %v", err) } fmt.Printf("Given name contains 'oh': %v\n", containsSubstring) // Output: Given name contains 'oh': true } ``` -------------------------------- ### Import FHIRPath Package in Go Source: https://github.com/verily-src/fhirpath-go/blob/main/README.md Imports the necessary FHIRPath package for use in Go programs. This is the initial step before utilizing any FHIRPath functionalities. ```go import "github.com/verily-src/fhirpath-go/fhirpath" ``` -------------------------------- ### Compile and Evaluate FHIRPath Expressions in Go Source: https://context7.com/verily-src/fhirpath-go/llms.txt Compiles a FHIRPath expression string into an executable format and evaluates it against provided FHIR resources. Handles potential errors during compilation and evaluation, returning results as a collection or a string. ```go package main import ( "fmt" "log" "github.com/verily-src/fhirpath-go/fhirpath" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" dtpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/datatypes_go_proto" cpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/codes_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" ) func main() { // Create a sample Patient resource patient := &ppb.Patient{ Id: fhir.ID("123"), Active: fhir.Boolean(true), Gender: &ppb.Patient_GenderCode{ Value: cpb.AdministrativeGenderCode_FEMALE, }, BirthDate: fhir.MustParseDate("2000-03-22"), Name: []*dtpb.HumanName{ { Use: &dtpb.HumanName_UseCode{ Value: cpb.NameUseCode_OFFICIAL, }, Given: []*dtpb.String{fhir.String("Jane")}, Family: fhir.String("Doe"), }, { Use: &dtpb.HumanName_UseCode{ Value: cpb.NameUseCode_NICKNAME, }, Given: []*dtpb.String{fhir.String("Janie")}, Family: fhir.String("Doe"), }, }, } // Compile the FHIRPath expression expression, err := fhirpath.Compile("Patient.name.where(use = 'official').given") if err != nil { log.Fatalf("Failed to compile expression: %v", err) } // Evaluate the expression against the Patient resource result, err := expression.Evaluate([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate expression: %v", err) } // Process results (returns system.Collection) if len(result) > 0 { if givenName, ok := result[0].(*dtpb.String); ok { fmt.Printf("Official given name: %s\n", givenName.Value) // Output: Official given name: Jane } } // Use typed evaluation methods for convenience stringResult, err := expression.EvaluateAsString([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate as string: %v", err) } fmt.Printf("Given name as string: %s\n", stringResult) // Output: Given name as string: Jane } ``` -------------------------------- ### Add Custom Function to FHIRPath Compilation in Go Source: https://github.com/verily-src/fhirpath-go/blob/main/README.md Demonstrates how to add a custom function during the compilation of a FHIRPath expression. The custom function must accept a system.Collection as its first argument. ```go customFn := func (input system.Collection, args ...any) (system.Collection error) { fmt.Print("called custom fn") return input, nil } expression, err := fhirpath.Compile("print()", compopts.AddFunction("print", customFn)) ``` -------------------------------- ### Evaluate FHIRPath with External Constants in Go Source: https://context7.com/verily-src/fhirpath-go/llms.txt Evaluates FHIRPath expressions using external constant variables defined at runtime. This function takes a FHIR resource (Patient) and evaluates expressions against it, utilizing variables like %searchName, %minAge, and %allowedNames passed via evalopts.EnvVariable. It handles string, integer, and collection types for constants. Dependencies include 'fhirpath-go' and Google FHIR proto definitions. Returns a boolean or a FHIRPath value depending on the expression. ```go package main import ( "fmt" "log" "github.com/verily-src/fhirpath-go/fhirpath" "github.com/verily-src/fhirpath-go/fhirpath/evalopts" "github.com/verily-src/fhirpath-go/fhirpath/system" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" dtpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/datatypes_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" ) func main() { patient := &ppb.Patient{ Name: []*dtpb.HumanName{ { Given: []*dtpb.String{fhir.String("Bob")}, Family: fhir.String("Anderson"), }, }, } // Define external constant variables searchName := system.String("Bob") minAge := system.Integer(18) allowedNames := system.Collection{ system.String("Bob"), system.String("Alice"), system.String("Charlie"), } // Use external constant in expression with %variable syntax expr := fhirpath.MustCompile("Patient.name.given = %searchName") result, err := expr.EvaluateAsBool( []fhirpath.Resource{patient}, evalopts.EnvVariable("searchName", searchName), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Name matches search: %v\n", result) // Output: Name matches search: true // Use multiple external constants ageCheckExpr := fhirpath.MustCompile("%minAge > 0") isValidAge, err := ageCheckExpr.EvaluateAsBool( []fhirpath.Resource{patient}, evalopts.EnvVariable("minAge", minAge), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Minimum age is positive: %v\n", isValidAge) // Output: Minimum age is positive: true // Use collection as external constant nameInListExpr := fhirpath.MustCompile("Patient.name.given in %allowedNames") isAllowed, err := nameInListExpr.EvaluateAsBool( []fhirpath.Resource{patient}, evalopts.EnvVariable("allowedNames", allowedNames), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Name is in allowed list: %v\n", isAllowed) // Output: Name is in allowed list: true // Built-in %context variable (returns input collection) contextExpr := fhirpath.MustCompile("%context.name.given") contextResult, err := contextExpr.Evaluate([]fhirpath.Resource{patient}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Context result: %v\n", contextResult) // Output: Context result: [Bob] } ``` -------------------------------- ### Add Environment Variable to FHIRPath Evaluation in Go Source: https://github.com/verily-src/fhirpath-go/blob/main/README.md Shows how to define and use custom environment variables during FHIRPath expression evaluation. Variables can be primitive types or collections. ```go customVar := system.String("custom variable") result, err := expression.Evaluate([]fhirpath.Resource{someResource}, evalopts.EnvVariable("var", customVar)) ``` -------------------------------- ### Unmarshal JSON to FHIR Resource and Evaluate FHIRPath Expressions in Go Source: https://context7.com/verily-src/fhirpath-go/llms.txt This Go code snippet demonstrates unmarshalling JSON data into a FHIR resource using `fhirjson.UnmarshalNew`. It then evaluates FHIRPath expressions to extract specific data fields like 'family name', 'phone number', and 'city' from the resource. Finally, it shows how to marshal a FHIR resource object back into indented JSON format using `fhirjson.MarshalIndent`. Dependencies include the `fhirpath-go` and `google/fhir` libraries. ```go package main import ( "fmt" "log" "github.com/verily-src/fhirpath-go/fhirpath" "github.com/verily-src/fhirpath-go/fhirpath/fhirjson" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" dtpb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/datatypes_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" ) func main() { // JSON data from an API endpoint jsonData := []byte(`{ "resourceType": "Patient", "id": "example-patient", "name": [ { "use": "official", "given": ["Jane"], "family": "Smith" } ], "gender": "female", "birthDate": "1990-05-15", "telecom": [ { "system": "phone", "value": "555-1234", "use": "home" }, { "system": "email", "value": "jane.smith@example.com" } ], "address": [ { "line": ["123 Main St"], "city": "Springfield", "state": "IL", "postalCode": "62701", "country": "US" } ] }`) // Unmarshal JSON to FHIR resource resource, err := fhirjson.UnmarshalNew(jsonData) if err != nil { log.Fatalf("Failed to unmarshal: %v", err) } // Evaluate FHIRPath expressions on the unmarshalled resource familyExpr := fhirpath.MustCompile("Patient.name.family") familyName, err := familyExpr.EvaluateAsString([]fhirpath.Resource{resource}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Family name: %s\n", familyName) // Output: Family name: Smith // Extract phone number with where() function phoneExpr := fhirpath.MustCompile("Patient.telecom.where(system='phone').value") phoneNumber, err := phoneExpr.EvaluateAsString([]fhirpath.Resource{resource}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Phone: %s\n", phoneNumber) // Output: Phone: 555-1234 // Extract city from address cityExpr := fhirpath.MustCompile("Patient.address.city") city, err := cityExpr.EvaluateAsString([]fhirpath.Resource{resource}) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("City: %s\n", city) // Output: City: Springfield // Marshal back to JSON patient := &ppb.Patient{ Id: fhir.ID("new-patient"), Name: []*dtpb.HumanName{ { Given: []*dtpb.String{fhir.String("Bob")}, Family: fhir.String("Jones"), }, }, } jsonBytes, err := fhirjson.MarshalIndent(patient, "", " ") if err != nil { log.Fatalf("Failed to marshal: %v", err) } fmt.Printf("Marshalled JSON:\n%s\n", string(jsonBytes)) // Output: Marshalled JSON: // { // "resourceType": "Patient", // "id": "new-patient", // "name": [ // { // "given": ["Bob"], // "family": "Jones" // } // ] // } } ``` -------------------------------- ### Compile FHIRPath Expression in Go Source: https://github.com/verily-src/fhirpath-go/blob/main/README.md Compiles a FHIRPath expression string into an executable expression object. Handles potential compilation errors. ```go expression, err := fhirpath.Compile("Patient.name.given") if err != nil { panic("error while compiling FHIRPath") } ``` -------------------------------- ### Evaluate FHIRPath Expression in Go Source: https://github.com/verily-src/fhirpath-go/blob/main/README.md Evaluates a pre-compiled FHIRPath expression against a collection of FHIR resources. Returns a collection of results or an error. ```go inputResources := []fhirpath.Resource{somePatient, someMedication} result, err := expression.Evaluate(inputResources) if err != nil { panic("error while running FHIRPath against resource") } ``` -------------------------------- ### Override Time for FHIRPath Evaluation in Go Source: https://context7.com/verily-src/fhirpath-go/llms.txt This Go code snippet demonstrates how to override the current time for FHIRPath expressions like 'now()' and 'today()'. It utilizes the `evalopts.OverrideTime` option to set a specific test time, ensuring reproducible results for time-dependent queries. This is crucial for testing and scenarios requiring consistent time-based logic. ```go package main import ( "context" "fmt" "log" "time" "github.com/verily-src/fhirpath-go/fhirpath" "github.com/verily-src/fhirpath-go/fhirpath/evalopts" ppb "github.com/google/fhir/go/proto/google/fhir/proto/r4/core/resources/patient_go_proto" "github.com/verily-src/fhirpath-go/internal/fhir" ) func main() { patient := &ppb.Patient{ Id: fhir.ID("patient-123"), BirthDate: fhir.MustParseDate("1990-05-15"), } // Override time for time-based expressions testTime := time.Date(2024, 12, 25, 15, 30, 0, 0, time.UTC) nowExpr := fhirpath.MustCompile("now()") nowResult, err := nowExpr.Evaluate( []fhirpath.Resource{patient}, evalopts.OverrideTime(testTime), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("now() with override: %v\n", nowResult) // Output: now() with override: [2024-12-25T15:30:00Z] todayExpr := fhirpath.MustCompile("today()") todayResult, err := todayExpr.Evaluate( []fhirpath.Resource{patient}, evalopts.OverrideTime(testTime), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("today() with override: %v\n", todayResult) // Output: today() with override: [2024-12-25] // Use Go context for cancellation ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() longExpr := fhirpath.MustCompile("Patient.name.given") result, err := longExpr.Evaluate( []fhirpath.Resource{patient}, evalopts.WithContext(ctx), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Evaluation with context: %v\n", result) // Output: Evaluation with context: [] // Combine multiple evaluation options multiExpr := fhirpath.MustCompile("today() = @2024-12-25") isToday, err := multiExpr.EvaluateAsBool( []fhirpath.Resource{patient}, evalopts.OverrideTime(testTime), evalopts.WithContext(ctx), ) if err != nil { log.Fatalf("Failed to evaluate: %v", err) } fmt.Printf("Is today 2024-12-25: %v\n", isToday) // Output: Is today 2024-12-25: true } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.