### Install go-version Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/hashicorp/go-version/README.md Use the standard go get command to add the library to your project. ```bash $ go get github.com/hashicorp/go-version ``` -------------------------------- ### Run a Basic Mux Server Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/gorilla/mux/README.md A complete example demonstrating how to initialize a router and start an HTTP server. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Install the YAML package Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/gopkg.in/yaml.v3/README.md Use the go get command to install the package into your Go environment. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Create and Run a SOCKS5 Server Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/cloudfoundry/go-socks5/README.md This example demonstrates how to create a SOCKS5 server with default configuration and start listening for TCP connections on a specified address and port. Ensure the 'socks5' package is imported. ```go // Create a SOCKS5 server conf := &socks5.Config{} server, err := socks5.New(conf) if err != nil { panic(err) } // Create SOCKS5 proxy on localhost port 8000 if err := server.ListenAndServe("tcp", "127.0.0.1:8000"); err != nil { panic(err) } ``` -------------------------------- ### Ginkgo Spec Example for Library System Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md This example demonstrates a full Ginkgo test suite for a library system. It includes setup with BeforeEach, various test scenarios with When and Context, and assertions using Gomega's Expect. Use this for complex integration or behavior-driven tests. ```go import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ... ) var _ = Describe("Checking books out of the library", Label("library"), func() { var library *libraries.Library var book *books.Book var valjean *users.User BeforeEach(func() { library = libraries.NewClient() book = &books.Book{ Title: "Les Miserables", Author: "Victor Hugo", } valjean = users.NewUser("Jean Valjean") }) When("the library has the book in question", func() { BeforeEach(func(ctx SpecContext) { Expect(library.Store(ctx, book)).To(Succeed()) }) Context("and the book is available", func() { It("lends it to the reader", func(ctx SpecContext) { Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books()).To(ContainElement(book)) Expect(library.UserWithBook(ctx, book)).To(Equal(valjean)) }, SpecTimeout(time.Second * 5)) }) Context("but the book has already been checked out", func() { var javert *users.User BeforeEach(func(ctx SpecContext) { javert = users.NewUser("Javert") Expect(javert.Checkout(ctx, library, "Les Miserables")).To(Succeed()) }) It("tells the user", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is currently checked out")) }, SpecTimeout(time.Second * 5)) It("lets the user place a hold and get notified later", func(ctx SpecContext) { Expect(valjean.Hold(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Holds(ctx)).To(ContainElement(book)) By("when Javert returns the book") Expect(javert.Return(ctx, library, book)).To(Succeed()) By("it eventually informs Valjean") notification := "Les Miserables is ready for pick up" Eventually(ctx, valjean.Notifications).Should(ContainElement(notification)) Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books(ctx)).To(ContainElement(book)) Expect(valjean.Holds(ctx)).To(BeEmpty()) }, SpecTimeout(time.Second * 10)) }) }) When("the library does not have the book in question", func() { It("tells the reader the book is unavailable", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is not in the library catalog")) }, SpecTimeout(time.Second * 5)) }) }) ``` -------------------------------- ### Install lz4 Command-Line Tool Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/pierrec/lz4/README.md Use 'go install' to build and install the lz4c command-line interface tool. ```go go install github.com/pierrec/lz4/cmd/lz4c ``` -------------------------------- ### Full Mux Server Example in Go Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md A complete, runnable example of a basic Mux-based HTTP server in Go, demonstrating route registration and server startup. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Install lz4 Package Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/pierrec/lz4/README.md Use 'go get' to install the lz4 package for use in your Go projects. ```go go get github.com/pierrec/lz4 ``` -------------------------------- ### Install Compression Library Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/dsnet/compress/README.md Command to install the library using the Go toolchain. Requires Go 1.7 or higher. ```bash go get -u github.com/dsnet/compress ``` -------------------------------- ### Install Archiver CLI Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/mholt/archiver/README.md Install the Archiver command-line tool using go get. This command ensures you have the latest version. ```bash go get -u github.com/mholt/archiver/cmd/arc ``` -------------------------------- ### Install Gorilla Mux Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/gorilla/mux/README.md Use this command to install the gorilla/mux package with a correctly configured Go toolchain. ```go go get -u github.com/gorilla/mux ``` -------------------------------- ### Install and Use gxz Command Line Tool Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/ulikunitz/xz/README.md Commands for installing the gxz utility and performing compression or decompression operations on files. ```bash $ go get github.com/ulikunitz/xz/cmd/gxz ``` ```bash $ gxz bigfile ``` ```bash $ gxz -d bigfile.xz ``` -------------------------------- ### Install Diego-Beta Plugin Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/nora/README.md Installs the Diego-Beta plugin from the CF-Community repository. Ensure you have cf 6.10+ installed. ```sh cf add-plugin-repo CF-Community http://plugins.cloudfoundry.org/ cf install-plugin Diego-Beta -r CF-Community ``` -------------------------------- ### Combining Matchers in Gorilla Mux Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/gorilla/mux/README.md Chain multiple matchers like `Host`, `Methods`, and `Schemes` to define a precise route. This example matches GET requests on http://www.example.com/products. ```go r.HandleFunc("/products", ProductsHandler). Host("www.example.com"). Methods("GET"). Schemes("http") ``` -------------------------------- ### Basic Broker Configuration Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/service_broker/README.md Example of a standard catalog configuration for the broker. ```json { "catalog": { "sleep_seconds": 0, "status": 200, "body": { "key": "value" } } } ``` -------------------------------- ### Implement Basic Logging Middleware Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md A simple middleware example that logs the request URI before passing control to the next handler. ```go func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Do stuff here log.Println(r.RequestURI) // Call the next handler, which can be another middleware in the chain, or the final handler. next.ServeHTTP(w, r) }) } ``` -------------------------------- ### Serving Static Files with Gorilla Mux Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/gorilla/mux/README.md Use `PathPrefix` with `http.StripPrefix` and `http.FileServer` to serve static files from a directory. This example serves files under `/static/` from the current directory. ```go func main() { var dir string flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.Parse() r := mux.NewRouter() // This will serve files under http://localhost:8000/static/ r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) srv := &http.Server{ Handler: r, Addr: "127.0.0.1:8000", // Good practice: enforce timeouts for servers you create! WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } ``` -------------------------------- ### GET /env Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/README.md Prints environment variables. ```APIDOC ## GET /env ### Description Prints out the entire environment as a serialized Ruby hash. ### Method GET ### Endpoint /env ``` -------------------------------- ### POST /stress_testers Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/README.md Starts stress tester processes. ```APIDOC ## POST /stress_testers ### Description Starts the stress tester with specified cpu and io processes. ### Method POST ### Endpoint /stress_testers ### Parameters #### Query Parameters - **cpu** (integer) - Required - Number of cpu processes - **io** (integer) - Required - Number of io processes ``` -------------------------------- ### GET / Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/README.md Returns a simple greeting. ```APIDOC ## GET / ### Description Returns a greeting from Dora. ### Method GET ### Endpoint / ``` -------------------------------- ### Get CAPI BARAS repository Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/README.md Use this command to check out the `capi-bara-tests` repository and ensure it's added to your `$GOPATH`. A warning about no buildable Go source files can be ignored. ```bash go get -d github.com/cloudfoundry/capi-bara-tests ``` -------------------------------- ### Configure Route Matchers Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md Examples of various constraints that can be applied to routes to restrict matching based on host, path, methods, schemes, headers, or queries. ```go r := mux.NewRouter() // Only matches if domain is "www.example.com". r.Host("www.example.com") // Matches a dynamic subdomain. r.Host("{subdomain:[a-z]+}.example.com") ``` ```go r.PathPrefix("/products/") ``` ```go r.Methods("GET", "POST") ``` ```go r.Schemes("https") ``` ```go r.Headers("X-Requested-With", "XMLHttpRequest") ``` ```go r.Queries("key", "value") ``` ```go r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { return r.ProtoMajor == 0 }) ``` ```go r.HandleFunc("/products", ProductsHandler). Host("www.example.com"). Methods("GET"). Schemes("http") ``` -------------------------------- ### Example cookie file format Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/README.md The expected structure of the cookie file generated by libcurl. ```text # Netscape HTTP Cookie File # https://curl.haxx.se/docs/http-cookies.html # This file was generated by libcurl! Edit at your own risk. dora.yourdomain.com FALSE / FALSE 0 JSESSIONID 342b98fe-b43c-4642-7d59-eeee #HttpOnly_dora.yourdomain.com FALSE / FALSE 0 __VCAP_ID__ 342b98fe-b43c-4642-7d59-eeee ``` -------------------------------- ### Manage Cloud Foundry Applications with V3 API Helpers Source: https://context7.com/cloudfoundry/capi-bara-tests/llms.txt Utilize Go helper functions to perform lifecycle operations on Cloud Foundry applications, such as creation, starting, stopping, scaling, and deletion, by interacting with the V3 API. ```go package example import ( . "github.com/cloudfoundry/capi-bara-tests/helpers/v3_helpers" ) func ManageApp() { // Create a new application appGUID := CreateApp("my-app", spaceGUID, `{"FOO":"bar"}`) // Create a Docker-based application dockerAppGUID := CreateDockerApp("docker-app", spaceGUID, `{"KEY":"value"}`) // Start the application StartApp(appGUID) // Stop the application StopApp(appGUID) // Restart the application RestartApp(appGUID) // Scale the application ScaleApp(appGUID, 4) // Scale to 4 instances // Update environment variables UpdateEnvironmentVariables(appGUID, `{"NEW_VAR":"new_value"}`) // Delete the application DeleteApp(appGUID) } ``` -------------------------------- ### Subrouters with Path Prefixes in Gorilla Mux Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/gorilla/mux/README.md When a subrouter has a `PathPrefix`, inner routes are appended to it. This example defines routes under `/products/`. ```go r := mux.NewRouter() s := r.PathPrefix("/products").Subrouter() // "/products/" s.HandleFunc("/", ProductsHandler) // "/products/{key}/" s.HandleFunc("/{key}/", ProductHandler) // "/products/{key}/details" s.HandleFunc("/{key}/details", ProductDetailsHandler) ``` -------------------------------- ### Default Endpoint Configuration Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/service_broker/README.md Define fallback behavior when no specific plan GUID is matched. ```json { "provision": { "default": { "sleep_seconds": 0, "status": 200, "body": {} } } } ``` -------------------------------- ### YAML processing output Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/gopkg.in/yaml.v3/README.md The expected console output after running the provided Go example. ```text --- t: {Easy! {2 [3 4]}} --- t dump: a: Easy! b: c: 2 d: [3, 4] --- m: map[a:Easy! b:map[c:2 d:[3 4]]] --- m dump: a: Easy! b: c: 2 d: - 3 - 4 ``` -------------------------------- ### Graceful HTTP Server Shutdown with Gorilla Mux Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md Implement graceful shutdown for an HTTP server using Gorilla Mux. This example configures timeouts and handles SIGINT signals to allow existing connections to complete before exiting. Requires Go 1.8+. ```Go package main import ( "context" "flag" "log" "net/http" "os" "os/signal" "time" "github.com/gorilla/mux" ) func main() { var wait time.Duration flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m") flag.Parse() r := mux.NewRouter() // Add your routes as needed srv := &http.Server{ Addr: "0.0.0.0:8080", // Good practice to set timeouts to avoid Slowloris attacks. WriteTimeout: time.Second * 15, ReadTimeout: time.Second * 15, IdleTimeout: time.Second * 60, Handler: r, // Pass our instance of gorilla/mux in. } // Run our server in a goroutine so that it doesn't block. go func() { if err := srv.ListenAndServe(); err != nil { log.Println(err) } }() c := make(chan os.Signal, 1) // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C) // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught. signal.Notify(c, os.Interrupt) // Block until we receive our signal. <-c // Create a deadline to wait for. ctx, cancel := context.WithTimeout(context.Background(), wait) defer cancel() // Doesn't block if no connections, but will otherwise wait // until the timeout deadline. srv.Shutdown(ctx) // Optionally, you could run srv.Shutdown in a goroutine and block on // <-ctx.Done() if your application should wait for other services // to finalize based on context cancellation. log.Println("shutting down") os.Exit(0) } ``` -------------------------------- ### Path Prefix Matching in Gorilla Mux Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/gorilla/mux/README.md Use `r.PathPrefix()` to match requests that start with a specific path. This is useful for grouping related routes. ```go r.PathPrefix("/products/") ``` -------------------------------- ### Serve Static Files Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md Use PathPrefix with a file server to serve static assets from a directory. ```go func main() { var dir string flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.Parse() r := mux.NewRouter() // This will serve files under http://localhost:8000/static/ r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) srv := &http.Server{ Handler: r, Addr: "127.0.0.1:8000", // Good practice: enforce timeouts for servers you create! WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } ``` -------------------------------- ### Stage Application Packages and Builds with V3 API Helpers Source: https://context7.com/cloudfoundry/capi-bara-tests/llms.txt Manage the application staging process using Go helper functions. This includes creating packages, uploading source code, staging with buildpacks, and assigning droplets to applications. ```go package example import ( . "github.com/cloudfoundry/capi-bara-tests/helpers/v3_helpers" ) func StageApp(appGUID string, config Config) string { // Create a new package for the app packageGUID := CreatePackage(appGUID) // Build upload URL uploadURL := fmt.Sprintf("%s%s/v3/packages/%s/upload", config.Protocol(), config.GetApiEndpoint(), packageGUID) // Upload the package (zip file) UploadPackage(uploadURL, "/path/to/app.zip") // Wait for package to be ready WaitForPackageToBeReady(packageGUID) // Stage the package with specified buildpack buildGUID := StagePackage(packageGUID, "buildpack", "ruby_buildpack") // Wait for build to complete WaitForBuildToStage(buildGUID) // Get the droplet GUID from the completed build dropletGUID := GetDropletFromBuild(buildGUID) // Assign the droplet to the app AssignDropletToApp(appGUID, dropletGUID) return dropletGUID } ``` -------------------------------- ### Import the archiver package Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/mholt/archiver/README.md Include the library in your Go project. ```go import "github.com/mholt/archiver" ``` -------------------------------- ### GET /health Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/README.md Returns health status. ```APIDOC ## GET /health ### Description Returns 500 the first 3 times you call it, "I'm alive" thereafter. ### Method GET ### Endpoint /health ``` -------------------------------- ### Generate and map instance cookie jars Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/scripts/README.md Create directories for cookie jars, generate instance cookie jars using `get_instance_cookie_jars.sh` for sticky sessions, and then map these cookie jars to instance IP addresses and indices using `map_cookie_jars.rb`. ```bash mkdir cookie_jars get_instance_cookie_jars.sh -e 8 -m 40 -d cookie_jars map_cookie_jars_to_instances.rb > map.out ``` -------------------------------- ### Retrieve Cloud Foundry Resource GUIDs in Go Source: https://context7.com/cloudfoundry/capi-bara-tests/llms.txt Retrieves GUIDs for spaces, organizations, and domains by name, enabling lookup of Cloud Foundry resources for use in other API operations. These helpers are essential for programmatically interacting with Cloud Foundry resources. ```go package example import ( . "github.com/cloudfoundry/capi-bara-tests/helpers/v3_helpers" ) func GetResources() { // Get space GUID from name spaceGUID := GetSpaceGuidFromName("development") // Get organization GUID from name orgGUID := GetOrgGUIDFromName("my-org") // Get domain GUID from name domainGUID := GetDomainGUIDFromName("apps.example.com") // Use these GUIDs in other API calls appGUID := CreateApp("my-app", spaceGUID, "{}") CreateAndMapRoute(appGUID, spaceGUID, domainGUID, "my-app") } ``` -------------------------------- ### GET /find/:filename Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/README.md Finds a file in the instance. ```APIDOC ## GET /find/:filename ### Description Finds a file in your instance. ### Method GET ### Endpoint /find/:filename ### Parameters #### Path Parameters - **filename** (string) - Required - The name of the file to find ``` -------------------------------- ### Create Root Logger Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/go-logr/logr/README.md Initialize the root logger with a chosen implementation and parameters early in the application's lifecycle. ```go func main() { // ... other setup code ... // Create the "root" logger. We have chosen the "logimpl" implementation, // which takes some initial parameters and returns a logr.Logger. logger := logimpl.New(param1, param2) // ... other setup code ... ``` -------------------------------- ### GET /id Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/README.md Returns the ID of the current app instance. ```APIDOC ## GET /id ### Description Returns the unique ID of the instance. ### Method GET ### Endpoint /id ``` -------------------------------- ### Build URL with Host and Path Variables Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/catnip/vendor/github.com/gorilla/mux/README.md Construct a full URL for a route that includes host and path variables. All specified variables must be provided and conform to their patterns. ```go url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42") ``` -------------------------------- ### Deploy the Async Broker Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/service_broker/README.md Command to push the broker application to Cloud Foundry. ```bash cf push async-broker ``` -------------------------------- ### Compress and Uncompress String with lz4 Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/pierrec/lz4/README.md Demonstrates how to compress a string using lz4.NewWriter and then uncompress it using lz4.NewReader via an io.Pipe. Ensure writers are closed to terminate the pipe. ```go // Compress and uncompress an input string. s := "hello world" r := strings.NewReader(s) // The pipe will uncompress the data from the writer. pr, pw := io.Pipe() zw := lz4.NewWriter(pw) zr := lz4.NewReader(pr) go func() { // Compress the input string. _, _ = io.Copy(zw, r) _ = zw.Close() // Make sure the writer is closed _ = pw.Close() // Terminate the pipe }() _, _ = io.Copy(os.Stdout, zr) // Output: // hello world ``` -------------------------------- ### List Routes with Router.Walk Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/catnip/vendor/github.com/gorilla/mux/README.md Iterate over all registered routes to inspect path templates, regex patterns, and allowed methods. ```go package main import ( "fmt" "net/http" "strings" "github.com/gorilla/mux" ) func handler(w http.ResponseWriter, r *http.Request) { return } func main() { r := mux.NewRouter() r.HandleFunc("/", handler) r.Methods("POST").HandleFunc("/products", handler) r.Methods("GET").HandleFunc("/articles", handler) r.Methods("GET", "PUT").HandleFunc("/articles/{id}", handler) r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { t, err := route.GetPathTemplate() if err != nil { return err } // p will contain regular expression is compatible with regular expression in Perl, Python, and other languages. // for instance the regular expression for path '/articles/{id}' will be '^/articles/(?P[^/]+)$' p, err := route.GetPathRegexp() if err != nil { return err } m, err := route.GetMethods() if err != nil { return err } fmt.Println(strings.Join(m, ","), t, p) return nil }) http.Handle("/", r) } ``` -------------------------------- ### Configure and use a Zip archiver Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/mholt/archiver/README.md Create a specific archiver instance to customize compression settings and behavior. ```go z := archiver.Zip{ CompressionLevel: flate.DefaultCompression, MkdirAll: true, SelectiveCompression: true, ContinueOnError: false, OverwriteExisting: false, ImplicitTopLevelFolder: false, } err := z.Archive([]string{"testdata", "other/file.txt"}, "/Users/matt/Desktop/test.zip") ``` -------------------------------- ### Plan-Dependent Endpoint Configuration Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/service_broker/README.md Configure endpoint behavior based on specific plan GUIDs. ```json { "provision": { "sync-plan-guid": { "sleep_seconds": 0, "status": 200, "body": {} }, "async-plan-guid": { "sleep_seconds": 0, "status": 202, "body": { "last_operation": { "state": "in progress" } } } } } ``` -------------------------------- ### CORS request response output Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md Example output showing the headers returned by the server after a successful CORS request. ```bash * Trying ::1... * TCP_NODELAY set * Connected to localhost (::1) port 8080 (#0) > GET /foo HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.59.0 > Accept: */* > < HTTP/1.1 200 OK < Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS < Access-Control-Allow-Origin: * < Date: Fri, 28 Jun 2019 20:13:30 GMT < Content-Length: 3 < Content-Type: text/plain; charset=utf-8 < * Connection #0 to host localhost left intact foo ``` -------------------------------- ### Check Version Constraints Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/hashicorp/go-version/README.md Define version constraints and verify if a specific version satisfies them. ```go v1, err := version.NewVersion("1.2") // Constraints example. constraints, err := version.NewConstraint(">= 1.0, < 1.4") if constraints.Check(v1) { fmt.Printf("%s satisfies constraints %s", v1, constraints) } ``` -------------------------------- ### Configure integration tests Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/README.md Create an `integration_config.json` file with API endpoint, domain, admin credentials, and SSL validation settings. Export the path to this configuration file for use in tests. ```bash cat > integration_config.json <[^/]+)$' p, err := route.GetPathRegexp() if err != nil { return err } m, err := route.GetMethods() if err != nil { return err } fmt.Println(strings.Join(m, ","), t, p) return nil }) http.Handle("/", r) } ``` -------------------------------- ### Handler with Route Variable in Go Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md Defines an HTTP route with a variable part '/metrics/{type}'. This setup is used for testing dynamic routes. ```go package main import ( "log" "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() // A route with a route variable: r.HandleFunc("/metrics/{type}", MetricsHandler) log.Fatal(http.ListenAndServe("localhost:8080", r)) } ``` -------------------------------- ### Parse and Compare Versions Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/hashicorp/go-version/README.md Create version objects from strings and use comparison methods like LessThan. ```go v1, err := version.NewVersion("1.2") v2, err := version.NewVersion("1.5+metadata") // Comparison example. There is also GreaterThan, Equal, and just // a simple Compare that returns an int allowing easy >=, <=, etc. if v1.LessThan(v2) { fmt.Printf("%s is less than %s", v1, v2) } ``` -------------------------------- ### Create and Parse UUIDs in Go Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/satori/go.uuid/README.md Demonstrates creating a Version 4 UUID and parsing a UUID from a string. Ensure the 'github.com/satori/go.uuid' package is imported. ```go package main import ( "fmt" "github.com/satori/go.uuid" ) func main() { // Creating UUID Version 4 u1 := uuid.NewV4() fmt.Printf("UUIDv4: %s\n", u1) // Parsing UUID from string input u2, err := uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8") if err != nil { fmt.Printf("Something gone wrong: %s", err) } fmt.Printf("Successfully parsed: %s", u2) } ``` -------------------------------- ### Compress and Decompress Data with xz API Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/ulikunitz/xz/README.md Demonstrates using the xz package to compress a string into a buffer and subsequently decompress it to standard output. ```go package main import ( "bytes" "io" "log" "os" "github.com/ulikunitz/xz" ) func main() { const text = "The quick brown fox jumps over the lazy dog.\n" var buf bytes.Buffer // compress text w, err := xz.NewWriter(&buf) if err != nil { log.Fatalf("xz.NewWriter error %s", err) } if _, err := io.WriteString(w, text); err != nil { log.Fatalf("WriteString error %s", err) } if err := w.Close(); err != nil { log.Fatalf("w.Close error %s", err) } // decompress buffer and write output to stdout r, err := xz.NewReader(&buf) if err != nil { log.Fatalf("NewReader error %s", err) } if _, err = io.Copy(os.Stdout, r); err != nil { log.Fatalf("io.Copy error %s", err) } } ``` -------------------------------- ### Start a socat drain server Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/scripts/README.md Use `socat` to listen on a TCP port, pipe the received data through Ruby to add timestamps and flush stdout, and log the output to a file. This is useful for capturing logs from a drain. ```bash bosh ssh router_z1 sudo -i apt-get install socat mkdir -p /var/vcap/sys/logs/drain socat -u TCP4-LISTEN:4567,reuseaddr,fork - | \ ruby -ne 'print Time.now.strftime("%FT%T.%N%:z") + " " + $_; $stdout.flush' | \ tee /var/vcap/sys/logs/drain/messages.log ``` -------------------------------- ### Manage Deployments Source: https://context7.com/cloudfoundry/capi-bara-tests/llms.txt Functions for creating rolling and canary deployments, managing their lifecycle, and verifying status. ```go package example import ( . "github.com/cloudfoundry/capi-bara-tests/helpers/v3_helpers" ) func DeployApp(appGUID, dropletGUID string) { // Create a rolling deployment deploymentGUID := CreateDeployment(appGUID, "rolling", 2) // max_in_flight=2 // Create a deployment for a specific droplet deploymentGUID = CreateDeploymentForDroplet(appGUID, dropletGUID, "rolling") // Create a canary deployment canaryDeploymentGUID := CreateDeploymentForDroplet(appGUID, dropletGUID, "canary") // Create canary deployment with custom step weights stepWeights := []int{1, 50, 75, 99} canaryWithStepsGUID := CreateCanaryDeploymentWithWeightsForDroplet( appGUID, dropletGUID, stepWeights) // Wait for deployment to reach PAUSED status (canary) WaitUntilDeploymentReachesStatus(canaryDeploymentGUID, "ACTIVE", "PAUSED") // Continue a paused canary deployment ContinueDeployment(canaryDeploymentGUID) // Wait for deployment to complete WaitUntilDeploymentReachesStatus(deploymentGUID, "FINALIZED", "DEPLOYED") // Cancel a deployment (rollback) CancelDeployment(deploymentGUID) // Verify cancellation WaitUntilDeploymentReachesStatus(deploymentGUID, "FINALIZED", "CANCELED") } ``` -------------------------------- ### Commit, Push, and Create GitHub Release Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/onsi/gomega/RELEASING.md Commands to commit changes, push to the repository, and create a new GitHub release. Replace 'vM.m.p' with the actual version number. ```bash git commit -m "vM.m.p" git push gh release create "vM.m.p" git fetch --tags origin master ``` -------------------------------- ### POST /session Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/README.md Sets up cookies for a sticky session. ```APIDOC ## POST /session ### Description Sets up the cookies for a sticky session. ### Method POST ### Endpoint /session ``` -------------------------------- ### Register Authentication Middleware Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md Configuring and attaching the authentication middleware to the router. ```go r := mux.NewRouter() r.HandleFunc("/", handler) amw := authenticationMiddleware{tokenUsers: make(map[string]string)} amw.Populate() r.Use(amw.Middleware) ``` -------------------------------- ### Migrate format strings to structured logging Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/go-logr/logr/README.md Convert traditional format-string logging calls into structured key-value pairs for better log processing. ```go klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err) ``` ```go logger.Error(err, "client returned an error", "code", responseCode) ``` ```go klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url) ``` ```go logger.V(4).Info("got a retry-after response when requesting url", "attempt", retries, "after seconds", seconds, "url", url) ``` ```go log.Printf("unable to reflect over type %T") ``` ```go logger.Info("unable to reflect over type", "type", fmt.Sprintf("%T")) ``` -------------------------------- ### Register Basic URL Paths and Handlers Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/gorilla/mux/README.md Register three routes mapping URL paths to handlers. This is equivalent to http.HandleFunc(). If an incoming request URL matches one of the paths, the corresponding handler is called. ```go func main() { r := mux.NewRouter() r.HandleFunc("/", HomeHandler) r.HandleFunc("/products", ProductsHandler) r.HandleFunc("/articles", ArticlesHandler) http.Handle("/", r) } ``` -------------------------------- ### Interact with the Configuration API Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/service_broker/README.md Commands to fetch, update, or reset the broker's configuration. ```bash curl /config ``` ```bash curl /config/all ``` ```bash curl /config -X POST -d @data.json ``` ```bash curl /config/reset -X POST ``` -------------------------------- ### HTTP Method Matching with Gorilla Mux Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/gorilla/mux/README.md Use `r.Methods()` to specify allowed HTTP methods for a route. Accepts a variadic list of method strings. ```go r.Methods("GET", "POST") ``` -------------------------------- ### Deploy Nora Application Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/nora/README.md Deploys the Nora application to CloudFoundry. Replace and with your desired values. ```sh ./make_a_nora ``` -------------------------------- ### Initialize sticky session cookies Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/README.md Request the session endpoint to set cookies and save them to a local file. ```bash curl dora.yourdomain.com/session -c my_cookies ``` -------------------------------- ### Run CAPI BARAS Tests Source: https://context7.com/cloudfoundry/capi-bara-tests/llms.txt Execute the BARAS test suite using the provided binary. Options include setting the configuration file path, running tests in parallel, and enabling verbose output. ```bash # Set configuration file path export CONFIG=$PWD/integration_config.json # Run all tests ./bin/test # Run tests in parallel (4 processes) ./bin/test -nodes=4 # Run with verbose output ./bin/test -v ``` -------------------------------- ### Match Headers with Regex Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/credhub-service-broker/vendor/github.com/gorilla/mux/README.md Use HeadersRegexp to match requests based on header values using regular expressions. ```go r.HeadersRegexp("Content-Type", "application/(text|json)") ``` -------------------------------- ### Manage Processes Source: https://context7.com/cloudfoundry/capi-bara-tests/llms.txt Functions for querying and configuring application processes, including scaling and health check settings. ```go package example import ( . "github.com/cloudfoundry/capi-bara-tests/helpers/v3_helpers" ) func ManageProcesses(appGUID string) { // Get all processes for an app processes := GetProcesses(appGUID, "my-app") // Get specific process by type webProcess := GetFirstProcessByType(processes, "web") // Get process by GUID process := GetProcessByGuid(webProcess.Guid) // Set command on a process SetCommandOnProcess(appGUID, "web", "bundle exec rackup config.ru -p $PORT") // Set health check timeout SetHealthCheckTimeoutOnProcess(appGUID, "web", 60) // Scale process memory ScaleProcess(appGUID, "web", "512") // 512 MB // Get process GUIDs for a type processGUIDs := GetProcessGuidsForType(appGUID, "web") // Get running instance count runningCount := GetRunningInstancesStats(processGUIDs[0]) } ``` -------------------------------- ### Execute all tests Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/README.md Run all test groups from the root directory of the `cf-acceptance-tests` project using this command. ```bash ./bin/test ``` -------------------------------- ### Route Registration with Path Variables Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md Define routes with dynamic path variables using {name} or {name:pattern}. Variables are captured until the next slash if no pattern is specified. ```go r := mux.NewRouter() r.HandleFunc("/products/{key}", ProductHandler) r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) ``` -------------------------------- ### Deploy and configure application with syslog drain Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/assets/dora/scripts/README.md Push a Cloud Foundry application named 'dora', create a syslog drain service named 'sc', bind the service to 'dora', and restart the application to enable log forwarding. ```bash cf push dora cf delete-service sc -f cf cups sc -l syslog://10.10.16.15:4567 cf bind-service dora sc cf restart dora ``` -------------------------------- ### Implement CORSMethodMiddleware in Go Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md Configures a router with CORSMethodMiddleware and a custom OPTIONS handler to manage CORS headers. Requires an OPTIONS method matcher on the route. ```go package main import ( "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() // IMPORTANT: you must specify an OPTIONS method matcher for the middleware to set CORS headers r.HandleFunc("/foo", fooHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodOptions) r.Use(mux.CORSMethodMiddleware(r)) http.ListenAndServe(":8080", r) } func fooHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == http.MethodOptions { return } w.Write([]byte("foo")) } ``` -------------------------------- ### Basic Route Registration Source: https://github.com/cloudfoundry/capi-bara-tests/blob/main/vendor/github.com/gorilla/mux/README.md Register basic URL paths and their corresponding handlers using mux.NewRouter(). This is compatible with http.Handle(). ```go func main() { r := mux.NewRouter() r.HandleFunc("/", HomeHandler) r.HandleFunc("/products", ProductsHandler) r.HandleFunc("/articles", ArticlesHandler) http.Handle("/", r) } ```