### Install pat library Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/bmizerany/pat/README.md Use the go get command to install the pat package. ```bash $ go get github.com/bmizerany/pat ``` -------------------------------- ### Example output Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/go.yaml.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 ``` -------------------------------- ### Install the YAML package Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/go.yaml.in/yaml/v3/README.md Use the go get command to add the package to your Go project. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Create a basic web server with pat Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/bmizerany/pat/README.md Example of setting up a simple HTTP server using pat to handle dynamic URL parameters. ```go package main import ( "io" "net/http" "github.com/bmizerany/pat" "log" ) // hello world, the web server func HelloServer(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, "+req.URL.Query().Get(":name")+"!\n") } func main() { m := pat.New() m.Get("/hello/:name", http.HandlerFunc(HelloServer)) // Register this pat with the default serve mux so that other packages // may also be exported. (i.e. /debug/pprof/*) http.Handle("/", m) err := http.ListenAndServe(":12345", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } ``` -------------------------------- ### Convert Format Strings to Structured Logs Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/go-logr/logr/README.md Examples demonstrating the migration from klog format-string logging to structured logr-style key-value logging. ```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) ``` -------------------------------- ### Install gouuid Package Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/nu7hatch/gouuid/README.md Use the `go` tool to install the gouuid package. This command fetches the latest version of the library. ```bash go get github.com/nu7hatch/gouuid ``` -------------------------------- ### Ginkgo Spec Example Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md An example of a Ginkgo spec demonstrating BeforeEach, When, Context, It, and Expect for testing library book checkout functionality. Includes SpecTimeout for test duration. ```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 Gomega Plugin for Claude Code Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/onsi/gomega/README.md Install the Gomega plugin for Claude Code to enable Gomega's matchers and features within the agent's testing environment. This can be done interactively or non-interactively. ```bash /plugin marketplace add onsi/gomega /plugin install gomega@gomega ``` ```bash claude plugin marketplace add onsi/gomega claude plugin install gomega@gomega ``` -------------------------------- ### Example Output with Debug Log Level Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/code.cloudfoundry.org/lager/v3/lagerflags/README.md When the application is run with the `--logLevel debug` flag, the output includes debug messages and indicates the current log level. ```text {"timestamp":"1464388983.540486336","source":"my-component","message":"my-component.starting","log_level":1,"data":{}} Current log level is debug ``` -------------------------------- ### Install Ginkgo Claude Code Plugin Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md Use these commands to add the Ginkgo plugin to your Claude Code environment. This enables Ginkgo's features within your project's specs. ```bash /plugin marketplace add onsi/ginkgo /plugin install ginkgo@ginkgo ``` ```bash claude plugin marketplace add onsi/ginkgo claude plugin install ginkgo@ginkgo ``` -------------------------------- ### Initialize Lager Logger with Flags Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/code.cloudfoundry.org/lager/v3/lagerflags/README.md Import and use `lagerflags` to add a logLevel flag to your application. Call `lagerflags.New()` to get a logger instance. This logger's level is determined by the `--logLevel` flag. ```go package main import ( "flag" "fmt" "code.cloudfoundry.org/lager/v3/lagerflags" "code.cloudfoundry.org/lager/v3" ) func main() { lagerflags.AddFlags(flag.CommandLine) flag.Parse() logger, reconfigurableSink := lagerflags.New("my-component") logger.Info("starting") // Display the current minimum log level fmt.Printf("Current log level is ") switch reconfigurableSink.GetMinLevel() { case lager.DEBUG: fmt.Println("debug") case lager.INFO: fmt.Println("info") case lager.ERROR: fmt.Println("error") case lager.FATAL: fmt.Println("fatal") } // Change the minimum log level dynamically reconfigurableSink.SetMinLevel(lager.ERROR) logger.Debug("will-not-log") } ``` -------------------------------- ### Run mkall.sh to Build Files (Old System) Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/golang.org/x/sys/unix/README.md Use this command to generate Go files for your current OS and architecture using the old build system. Ensure GOOS and GOARCH are set correctly. ```bash mkall.sh ``` -------------------------------- ### Initialize Dropsonde Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/cloudfoundry/dropsonde/README.md Initializes the library, logs, and metrics packages, and instruments the default HTTP handler. ```go import ( "github.com/cloudfoundry/dropsonde" ) func main() { dropsonde.Initialize("localhost:3457", "router", "z1", "0") } ``` -------------------------------- ### Show mkall.sh Commands (Old System) Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/golang.org/x/sys/unix/README.md View the commands that will be executed by mkall.sh without actually running them. Useful for understanding the build process. ```bash mkall.sh -n ``` -------------------------------- ### Initialize the root logger Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/go-logr/logr/README.md Create a root logger instance using a specific logging implementation early in the application 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 ... ``` -------------------------------- ### Initialize Rata Router Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/tedsuo/rata/README.md Create a new Rata router by combining the defined routes and handlers. The router implements the http.Handler interface. ```go router, err := rata.NewRouter(petRoutes, petHandlers) if err != nil { panic(err) } // The router is just an http.Handler, so it can be used to create a server in the usual fashion: server := httptest.NewServer(router) ``` -------------------------------- ### Check version against constraints Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/Masterminds/semver/v3/README.md Parses a constraint string and a version string, then evaluates if the version satisfies the constraint. ```go c, err := semver.NewConstraint(">= 1.2.3") if err != nil { // Handle constraint not being parsable. } v, err := semver.NewVersion("1.3") if err != nil { // Handle version not being parsable. } // Check if the version meets the constraints. The variable a will be true. a := c.Check(v) ``` -------------------------------- ### Create HTTP Handlers for Rata Routes Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/tedsuo/rata/README.md Create a map of HTTP handlers that correspond to the defined Rata route names. Ensure each route name has a matching handler. ```go petHandlers := rata.Handlers{ "get_pet": newGetPetHandler(), "create_pet": newCreatePetHandler(), "update_pet": newUpdatePetHandler(), "delete_pet": newDeletePetHandler() } ``` -------------------------------- ### Initialize a metric chainer Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/cloudfoundry/dropsonde/README.md Creates a chainer instance to accumulate tags before sending. ```go chainer := metrics.Value(name, value, unit). SetTag("req-mimetype", "json"). SetTag("name", v.Name) ``` -------------------------------- ### Send Application Logs Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/cloudfoundry/dropsonde/README.md Sends single log entries for platform-hosted applications. ```go logs.SendAppLog("b7ba6142-6e6a-4e0b-81c1-d7025888cce4", "An event happened!", "APP", "0") ``` -------------------------------- ### Send a metric with tags Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/cloudfoundry/dropsonde/README.md Applies tags to a metric value and sends it immediately. ```go err := metrics.Value(name, value, unit). SetTag("foo", "bar"). SetTag("bacon", 12). Send() ``` -------------------------------- ### Commit and Push Release Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/onsi/ginkgo/v2/RELEASING.md Commands to commit the version change, push to the repository, and create a GitHub release. ```bash git commit -m "vM.m.p" git push gh release create "vM.m.p" git fetch --tags origin master ``` -------------------------------- ### Load Slim-Sprig FuncMap in Go Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/go-task/slim-sprig/v3/README.md Load the Slim-Sprig FuncMap before parsing templates. Ensure the FuncMap is set prior to loading template files. ```go import ( "html/template" "github.com/go-task/slim-sprig" ) // This example illustrates that the FuncMap *must* be set before the // templates themselves are loaded. tpl := template.Must( template.New("base").Funcs(sprig.FuncMap()).ParseGlob("*.html") ) ``` -------------------------------- ### Run Ginkgo Specs in Parallel Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md Use the -p flag with the ginkgo command to run your specs in parallel. This is useful for speeding up test execution on multi-core systems. ```bash ginkgo -p ``` -------------------------------- ### Handle Format Strings in Values Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/go-logr/logr/README.md Pattern for cases where a format string is strictly necessary by using fmt.Sprintf within a key-value pair. ```go log.Printf("unable to reflect over type %T") ``` ```go logger.Info("unable to reflect over type", "type", fmt.Sprintf("%T")) ``` -------------------------------- ### Define API Routes with Rata Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/tedsuo/rata/README.md Define a set of API routes using Rata's Routes struct. Each route specifies a name, HTTP method, and path pattern with parameters. ```go petRoutes := rata.Routes{ {Name: "get_pet", Method: rata.GET, Path: "/people/:owner_id/pets/:pet_id"}, {Name: "create_pet", Method: rata.POST, Path: "/people/:owner_id/pets"}, {Name: "update_pet", Method: rata.PUT, Path: "/people/:owner_id/pets/:pet_id"}, {Name: "delete_pet", Method: rata.DELETE, Path: "/people/:owner_id/pets/:pet_id"}, } ``` -------------------------------- ### Unmarshal and Marshal YAML data Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/go.yaml.in/yaml/v3/README.md Demonstrates how to decode YAML into a struct or map, and encode them back into YAML format. Struct fields must be exported to be populated during unmarshaling. ```go package main import ( "fmt" "log" "go.yaml.in/yaml/v3" ) var data = ` a: Easy! b: c: 2 d: [3, 4] ` // Note: struct fields must be public in order for unmarshal to // correctly populate the data. type T struct { A string B struct { RenamedC int `yaml:"c"` D []int `yaml:",flow"` } } func main() { t := T{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) } ``` -------------------------------- ### Update CHANGELOG.md Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/onsi/ginkgo/v2/RELEASING.md Generates a list of changes since the last tag and prepends them to the CHANGELOG.md file. ```bash LAST_VERSION=$(git tag --sort=version:refname | tail -n1) CHANGES=$(git log --pretty=format:'- %s [%h]' HEAD...$LAST_VERSION) echo -e "## NEXT\n\n$CHANGES\n\n### Features\n\n### Fixes\n\n### Maintenance\n\n$(cat CHANGELOG.md)" > CHANGELOG.md ``` -------------------------------- ### Validate Version Against Constraint in Go Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/Masterminds/semver/v3/README.md Use the Validate method to check if a version meets a constraint and retrieve specific error messages if it fails. ```go c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") if err != nil { // Handle constraint not being parseable. } v, err := semver.NewVersion("1.3") if err != nil { // Handle version not being parseable. } // Validate a version against a constraint. a, msgs := c.Validate(v) // a is false for _, m := range msgs { fmt.Println(m) // Loops over the errors which would read // "1.3 is greater than 1.2.3" // "1.3 is less than 1.4" } ``` -------------------------------- ### Pass the logger to application components Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/go-logr/logr/README.md Inject the logger instance into application objects or pass it through the application structure. ```go app := createTheAppObject(logger) app.Run() ``` -------------------------------- ### System Call Interface Functions Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/golang.org/x/sys/unix/README.md These functions in `asm_${GOOS}_${GOARCH}.s` implement system call dispatch. They differ in the number of arguments they can pass to the kernel. ```go func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) ``` ```go func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) ``` ```go func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) ``` -------------------------------- ### Sort semantic versions Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/Masterminds/semver/v3/README.md Uses the standard library sort package with semver.Collection to order a slice of Version objects. ```go raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} vs := make([]*semver.Version, len(raw)) for i, r := range raw { v, err := semver.NewVersion(r) if err != nil { t.Errorf("Error parsing version: %s", err) } vs[i] = v } sort.Sort(semver.Collection(vs)) ``` -------------------------------- ### Parse a semantic version Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/Masterminds/semver/v3/README.md Parses a version string into a Version object, returning an error if the format is invalid. ```go v, err := semver.NewVersion("1.2.3-beta.1+build345") ``` -------------------------------- ### Process Application Log Streams Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/cloudfoundry/dropsonde/README.md Processes a stream of application logs from a socket connection. ```go logs.ScanLogStream("b7ba6142-6e6a-4e0b-81c1-d7025888cce4", "APP", "0", appLogSocketConnection) ``` -------------------------------- ### Send a chained metric Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/cloudfoundry/dropsonde/README.md Finalizes the chainer with additional tags and sends the metric. ```go err := chainer.SetTag("resp-state", "error"). SetTag("resp-code", http.StatusBadRequest). Send() ``` -------------------------------- ### Use the logger within a struct Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/go-logr/logr/README.md Store the logger in a struct and use it to emit logs within methods without knowledge of the underlying implementation. ```go type appObject struct { // ... other fields ... logger logr.Logger // ... other fields ... } func (app *appObject) Run() { app.logger.Info("starting up", "timestamp", time.Now()) // ... app code ... ``` -------------------------------- ### Use Slim-Sprig Functions in Templates Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/go-task/slim-sprig/v3/README.md Call Slim-Sprig functions within Go templates using lowercase names. Functions are chained using the pipe operator. ```go-template {{ "hello!" | upper | repeat 5 }} ``` -------------------------------- ### Generate mTLS Certs for Diego Cell and CC Uploader Source: https://github.com/cloudfoundry/cc-uploader/blob/main/README.md Generates certificates for mTLS connection between the Diego cell (client) and cc_uploader (server). Ensure you are in the 'certs/' directory before running. ```sh cd certs/ cp ../cc_uploader_ca_cn.crt ca.crt cp ../cc_uploader_ca_cn.key ca.key certstrap --depot-path . request-cert --passphrase '' --domain '*.localhost,localhost' --ip 127.0.0.1 mv \_.localhost.csr server.csr mv \_.localhost.key server.key certstrap --depot-path . sign server --CA ca --expires "10 years" certstrap --depot-path . request-cert --passphrase '' --common-name client --domain client --ip 127.0.0.1 certstrap --depot-path . sign client --CA ca --expires "10 years" ``` -------------------------------- ### Extract Path Parameters from Request Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/tedsuo/rata/README.md Access parameters from the URL path within an HTTP handler using rata.Param. Ensure the parameter name matches the one defined in the route path. ```go ownerId := rata.Param(request, "owner_id") ``` -------------------------------- ### Update a metric chainer Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/cloudfoundry/dropsonde/README.md Adds additional tags to an existing chainer instance. ```go chainer = chainer.SetTag("resp-mimetype", respType) ``` -------------------------------- ### Generate mTLS Certs for CC Uploader and Cloud Controller Source: https://github.com/cloudfoundry/cc-uploader/blob/main/README.md Generates CA, server, and client certificates for mTLS connection between cc_uploader and cloud_controller. Ensure you are in the 'fixtures' directory before running. ```sh cd fixtures echo "Generating CA" certstrap --depot-path . init --passphrase '' --common-name cc_uploader_ca_cn --expires "10 years" echo "Generating server csr" certstrap --depot-path . request-cert --passphrase '' --common-name cc_cn --domain cc_cn --ip 127.0.0.1 echo "Generating server cert" certstrap --depot-path . sign cc_cn --CA cc_uploader_ca_cn --expires "10 years" echo "Generating client csr" certstrap --depot-path . request-cert --passphrase '' --common-name cc_uploader_cn --domain cc_uploader_cn --ip 127.0.0.1 echo "Generating client cert" certstrap --depot-path . sign cc_uploader_cn --CA cc_uploader_ca_cn --expires "10 years" ``` -------------------------------- ### Generate HTTP Request with Rata Source: https://github.com/cloudfoundry/cc-uploader/blob/main/vendor/github.com/tedsuo/rata/README.md Create an http.Request object using Rata's RequestGenerator. This ensures requests conform to the defined API routes and parameters. ```go requestGenerator := rata.NewRequestGenerator(server.URL, petRoutes) // You can use the request generator to ensure you are creating a valid request: req, err := requestGenerator.CreateRequest("get_pet", rata.Params{"owner_id": "123", "pet_id": "5"}, nil) // The generated request can be used like any other http.Request object: res, err := http.DefaultClient.Do(req) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.