### Install sql-migrate CLI Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/rubenv/sql-migrate/README.md Installs the sql-migrate library and command-line program using go get. ```bash go get -v github.com/rubenv/sql-migrate/... ``` -------------------------------- ### Install Go-Diodes Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/code.cloudfoundry.org/go-diodes/README.md Use 'go get' to install the go-diodes library. ```bash go get code.cloudfoundry.org/go-diodes ``` -------------------------------- ### Install go-metrics Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/rcrowley/go-metrics/README.md Command to install the go-metrics library using go get. ```sh go get github.com/rcrowley/go-metrics ``` -------------------------------- ### Setup Test Database Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Commands to create the test database and run the PostgreSQL setup script. These are essential steps after starting the database cluster for testing. ```bash createdb psql --no-psqlrc -f testsetup/postgresql_setup.sql ``` -------------------------------- ### Implement a basic web server with pat Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/bmizerany/pat/README.md Example demonstrating how to define a route with a parameter and start a server using the pat muxer. ```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) } } ``` -------------------------------- ### Install NATS Go Client and Server Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/nats-io/go-nats/README.md Use 'go get' to install the NATS Go client and the NATS server. ```bash # Go client go get github.com/nats-io/go-nats # Server go get github.com/nats-io/gnatsd ``` -------------------------------- ### Install the YAML package Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/gopkg.in/yaml.v3/README.md Use the go get command to add the package to your project. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Install utfbom package Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/go.step.sm/crypto/internal/utils/utfbom/README.md Use the go get command to add the package to your Go workspace. ```bash go get -u github.com/dimchansky/utfbom ``` -------------------------------- ### Install NUID Library Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/nats-io/nuid/README.md Use the 'go get' command to install the NUID library for your Go project. ```bash go get github.com/nats-io/nuid ``` -------------------------------- ### Validator Package Installation and Usage Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/gopkg.in/validator.v2/README.md Instructions on how to install the validator package using go get and a basic example of its usage in Go code. ```APIDOC ## Installation Just use go get. ```bash go get gopkg.in/validator.v2 ``` And then just import the package into your own code. ```go import ( "gopkg.in/validator.v2" ) ``` ## Usage Please see http://godoc.org/gopkg.in/validator.v2 for detailed usage docs. A simple example would be. ```go type NewUserRequest struct { Username string `validate:"min=3,max=40,regexp=^[a-zA-Z]*$"` Name string `validate:"nonzero"` Age int `validate:"min=21"` Password string `validate:"min=8"` } nur := NewUserRequest{Username: "something", Age: 20} if errs := validator.Validate(nur); errs != nil { // values not valid, deal with errors here } ``` ``` -------------------------------- ### Install validator package Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/gopkg.in/validator.v2/README.md Use go get to install the package. ```bash go get gopkg.in/validator.v2 ``` -------------------------------- ### Full Test Example Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/st3v/glager/README.md A complete example showing how to instantiate a logger, log events, and verify them in a test. ```go import ( "code.cloudfoundry.com/lager" . "github.com/onsi/gomega" . "github.com/st3v/glager" ) ... // instantiate glager.TestLogger inside your test and logger := NewLogger("test") // pass logger to your code and use it in there to log stuff func(logger *lager.Logger) { logger.Info("myFunc", lager.Data(map[string]interface{}{ "event": "start", })) logger.Debug("myFunc", lager.Data(map[string]interface{}{ "some": "stuff", "more": "stuff", })) logger.Error("myFunc", errors.New("some error"), lager.Data(map[string]interface{}{ "details": "stuff", }), ) logger.Info("myFunc", lager.Data(map[string]interface{}{ "event": "done", })) }() ... // verify logging inside your test Expect(logger).To(HaveLogged( Info( Message("test.myFunc"), Data("event", "start"), ), Debug( Data("more", "stuff"), ), Error(AnyErr), )) ``` -------------------------------- ### Install urfave/cli package Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/codegangsta/cli/README.md Use the go get command to download the library into your Go workspace. ```bash $ go get github.com/urfave/cli ``` -------------------------------- ### Install the YAML package Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/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 ``` -------------------------------- ### Executing Commands and Application Setup Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/codegangsta/cli/README.md Running subcommands and inspecting visible application components. ```go fmt.Printf("%#v\n", c.App.Command("doo")) if c.Bool("infinite") { c.App.Run([]string{"app", "doo", "wop"}) } if c.Bool("forevar") { c.App.RunAsSubcommand(c) } c.App.Setup() fmt.Printf("%#v\n", c.App.VisibleCategories()) fmt.Printf("%#v\n", c.App.VisibleCommands()) fmt.Printf("%#v\n", c.App.VisibleFlags()) ``` -------------------------------- ### Install Go MySQL Driver Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/go-sql-driver/mysql/README.md Install the driver using the go tool. Ensure Git is installed and in your system's PATH. ```bash go get -u github.com/go-sql-driver/mysql ``` -------------------------------- ### Install sql-migrate CLI (Go 1.18+) Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/rubenv/sql-migrate/README.md Installs the sql-migrate library and command-line program for Go versions 1.18 and above using go install. ```bash go install github.com/rubenv/sql-migrate/...@latest ``` -------------------------------- ### Install Ginkgo Locally Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/proxy/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Installs the Ginkgo CLI locally. Ensure you have Go installed and configured. ```bash go install ./... ``` -------------------------------- ### Install Stats Package Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/montanaflynn/stats/README.md Use the go get command to add the stats package to your project. ```bash go get github.com/montanaflynn/stats ``` -------------------------------- ### Install sqlx Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/jmoiron/sqlx/README.md Use this command to add the sqlx library to your Go project. ```bash go get github.com/jmoiron/sqlx ``` -------------------------------- ### Install v1 release Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/codegangsta/cli/README.md Pin to the stable v1 release using gopkg.in. ```bash $ go get gopkg.in/urfave/cli.v1 ``` -------------------------------- ### Install S2 command-line tools Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/klauspost/compress/s2/README.md Installs the s2c and s2d binaries using the Go toolchain. ```bash go install github.com/klauspost/compress/s2/cmd/s2c@latest && go install github.com/klauspost/compress/s2/cmd/s2d@latest ``` -------------------------------- ### Example Container Metadata Structure Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/docs/03-troubleshooting.md This is an example of the store.json output. Locate the entry matching the container IP captured earlier to find the 'app_id', which is the application's GUID. ```json { "9bce657c-b92f-422b-60e0-227a66ad8b48" : { "metadata" : { "space_id" : "601577f3-7c2d-4d98-8029-0bd03b6a0682", "app_id" : "aa4117a2-5e34-4648-9d42-8260380267cc", "policy_group_id" : "aa4117a2-5e34-4648-9d42-8260380267cc", "org_id" : "ff585363-1164-49b2-bbf3-55dd0cb06597" }, "ip" : "10.255.29.4", "handle" : "9bce657c-b92f-422b-60e0-227a66ad8b48" }, "cf760bdc-ebf9-414e-4a88-29dc8820643e" : { "ip" : "10.255.29.3", "metadata" : { "policy_group_id" : "f028b20b-7203-4743-ab96-da2bf05fae45", "space_id" : "601577f3-7c2d-4d98-8029-0bd03b6a0682", "app_id" : "f028b20b-7203-4743-ab96-da2bf05fae45", "org_id" : "ff585363-1164-49b2-bbf3-55dd0cb06597" }, "handle" : "cf760bdc-ebf9-414e-4a88-29dc8820643e" } } ``` -------------------------------- ### Ginkgo and Gomega Example Spec Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/onsi/ginkgo/v2/README.md This example demonstrates a comprehensive Ginkgo spec for testing library operations. It includes setup with BeforeEach, various test scenarios with When and Context, and assertions using Gomega matchers. Use this for complex testing scenarios involving state management and asynchronous operations. ```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 sql-migrate with oci8 support Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/rubenv/sql-migrate/README.md Use this command to install the library and CLI tool with the oci8 tag. ```bash go get -tags oracle -v github.com/rubenv/sql-migrate/... ``` -------------------------------- ### Install pat library Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/bmizerany/pat/README.md Command to install the pat package using the Go toolchain. ```bash $ go get github.com/bmizerany/pat ``` -------------------------------- ### Install NKEYS via Go Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/nats-io/nkeys/README.md Use the standard Go toolchain to fetch the NKEYS package. ```bash $ go get github.com/nats-io/nkeys ``` -------------------------------- ### Example output Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/go.yaml.in/yaml/v3/README.md The expected output generated by the provided Go example code. ```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 tomll CLI Tool Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/pelletier/go-toml/README.md Install the 'tomll' command-line tool for linting TOML files. Ensure your Go environment is configured for installations. ```bash go install github.com/pelletier/go-toml/cmd/tomll tomll --help ``` -------------------------------- ### Install v2 branch Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/codegangsta/cli/README.md Install the unstable v2 branch using gopkg.in. ```bash $ go get gopkg.in/urfave/cli.v2 ``` -------------------------------- ### Go Module Dependency Example Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/cloudfoundry-community/go-uaa/README.md This is an example of how the `go.mod` file will look after adding the go-uaa dependency. ```go module github.com/cloudfoundry-community/go-uaa/cmd/test go 1.13 require github.com/cloudfoundry-community/go-uaa latest ``` -------------------------------- ### Install sql-migrate with godror support Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/rubenv/sql-migrate/README.md Use this command to install the library and CLI tool with the godror tag. ```bash go get -tags godror -v github.com/rubenv/sql-migrate/... ``` -------------------------------- ### DSN Examples for go-sql-driver/mysql Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/go-sql-driver/mysql/README.md Various examples of Data Source Name (DSN) strings for connecting to MySQL databases using different protocols, authentication methods, and configurations. ```go user@unix(/path/to/socket)/dbname ``` ```go root:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local ``` ```go user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true ``` ```go user:password@/dbname?sql_mode=TRADITIONAL ``` ```go user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci ``` ```go id:password@tcp(your-amazonaws-uri.com:3306)/dbname ``` ```go user:password@unix(/cloudsql/project-id:region-name:instance-name)/dbname ``` ```go user:password@tcp/dbname?charset=utf8mb4,utf8&sys_var=esc%40ped ``` ```go user:password@/dbname ``` ```go user:password@/ ``` -------------------------------- ### Start PostgreSQL for Testing Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/lib/pq/README.md Use Docker Compose to initialize a PostgreSQL instance for running tests. ```bash docker compose up -d ``` -------------------------------- ### Basic Connection Example Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/go-sql-driver/mysql/README.md Demonstrates how to establish a basic connection to a MySQL database using the driver. Ensure the DSN format is correct for your database. ```go import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname") if err != nil { log.Fatal(err) } defer db.Close() // ... use db } ``` -------------------------------- ### Install glager Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/st3v/glager/README.md Use the go get command to install the package. ```bash go get github.com/st3v/glager ``` -------------------------------- ### Setup Test Database and Extensions Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Use these commands to create a test database, enable necessary PostgreSQL extensions (hstore, ltree), and define a custom domain for testing. ```bash export PGDATABASE=pgx_test createdb psql -c 'create extension hstore;' psql -c 'create extension ltree;' psql -c 'create domain uint64 as numeric(20,0);' ``` -------------------------------- ### Full API Demonstration Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/codegangsta/cli/README.md A complete implementation of a CLI application using urfave/cli. This example demonstrates custom help templates, various flag types, and command lifecycle management. ```go package main import ( "errors" "flag" "fmt" "io" "io/ioutil" "os" "time" "github.com/urfave/cli" ) func init() { cli.AppHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n" cli.CommandHelpTemplate += "\nYMMV\n" cli.SubcommandHelpTemplate += "\nor something\n" cli.HelpFlag = cli.BoolFlag{Name: "halp"} cli.BashCompletionFlag = cli.BoolFlag{Name: "compgen", Hidden: true} cli.VersionFlag = cli.BoolFlag{Name: "print-version, V"} cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { fmt.Fprintf(w, "best of luck to you\n") } cli.VersionPrinter = func(c *cli.Context) { fmt.Fprintf(c.App.Writer, "version=%s\n", c.App.Version) } cli.OsExiter = func(c int) { fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", c) } cli.ErrWriter = ioutil.Discard cli.FlagStringer = func(fl cli.Flag) string { return fmt.Sprintf("\t\t%s", fl.GetName()) } } type hexWriter struct{} func (w *hexWriter) Write(p []byte) (int, error) { for _, b := range p { fmt.Printf("%x", b) } fmt.Printf("\n") return len(p), nil } type genericType struct{ s string } func (g *genericType) Set(value string) error { g.s = value return nil } func (g *genericType) String() string { return g.s } func main() { app := cli.NewApp() app.Name = "kənˈtrīv" app.Version = "19.99.0" app.Compiled = time.Now() app.Authors = []cli.Author{ cli.Author{ Name: "Example Human", Email: "human@example.com", }, } app.Copyright = "(c) 1999 Serious Enterprise" app.HelpName = "contrive" app.Usage = "demonstrate available API" app.UsageText = "contrive - demonstrating the available API" app.ArgsUsage = "[args and such]" app.Commands = []cli.Command{ cli.Command{ Name: "doo", Aliases: []string{"do"}, Category: "motion", Usage: "do the doo", UsageText: "doo - does the dooing", Description: "no really, there is a lot of dooing to be done", ArgsUsage: "[arrgh]", Flags: []cli.Flag{ cli.BoolFlag{Name: "forever, forevvarr"}, }, Subcommands: cli.Commands{ cli.Command{ Name: "wop", Action: wopAction, }, }, SkipFlagParsing: false, HideHelp: false, Hidden: false, HelpName: "doo!", BashComplete: func(c *cli.Context) { fmt.Fprintf(c.App.Writer, "--better\n") }, Before: func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "brace for impact\n") return nil }, After: func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "did we lose anyone?\n") return nil }, Action: func(c *cli.Context) error { c.Command.FullName() c.Command.HasName("wop") c.Command.Names() c.Command.VisibleFlags() fmt.Fprintf(c.App.Writer, "dodododododoodododddooooododododooo\n") if c.Bool("forever") { c.Command.Run(c) } return nil }, OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error { fmt.Fprintf(c.App.Writer, "for shame\n") return err }, }, } app.Flags = []cli.Flag{ cli.BoolFlag{Name: "fancy"}, cli.BoolTFlag{Name: "fancier"}, cli.DurationFlag{Name: "howlong, H", Value: time.Second * 3}, cli.Float64Flag{Name: "howmuch"}, cli.GenericFlag{Name: "wat", Value: &genericType{}}, cli.Int64Flag{Name: "longdistance"}, cli.Int64SliceFlag{Name: "intervals"}, cli.IntFlag{Name: "distance"}, cli.IntSliceFlag{Name: "times"}, cli.StringFlag{Name: "dance-move, d"}, cli.StringSliceFlag{Name: "names, N"}, cli.UintFlag{Name: "age"}, cli.Uint64Flag{Name: "bigage"}, } app.EnableBashCompletion = true app.HideHelp = false app.HideVersion = false app.BashComplete = func(c *cli.Context) { fmt.Fprintf(c.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n") } app.Before = func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n") return nil } app.After = func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "Phew!\n") return nil } app.CommandNotFound = func(c *cli.Context, command string) { fmt.Fprintf(c.App.Writer, "Thar be no %q here.\n", command) } app.OnUsageError = func(c *cli.Context, err error, isSubcommand bool) error { if isSubcommand { return err } fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err) return nil } app.Action = func(c *cli.Context) error { cli.DefaultAppComplete(c) cli.HandleExitCoder(errors.New("not an exit coder, though")) cli.ShowAppHelp(c) cli.ShowCommandCompletions(c, "nope") cli.ShowCommandHelp(c, "also-nope") ``` -------------------------------- ### GET /networking/v1/external/policies Response Body Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/docs/08-policy-server-api.md Example JSON response body for the GET /networking/v1/external/policies endpoint, showing total policies and policy details. ```json { "total_policies": 2, "policies": [ { "source": { "id": "1081ceac-f5c4-47a8-95e8-88e1e302efb5" }, "destination": { "id": "38f08df0-19df-4439-b4e9-61096d4301ea", "protocol": "tcp", "ports": { "start": 1234, "end": 1235 } } }, { "source": { "id": "308e7ef1-63f1-4a6c-978c-2e527cbb1c36" }, "destination": { "id": "308e7ef1-63f1-4a6c-978c-2e527cbb1c36", "protocol": "tcp", "ports": { "start": 1234, "end": 1235 } } } ] } ``` -------------------------------- ### Connect to PostgreSQL using pq.Config Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/lib/pq/README.md Configure connection parameters using pq.Config and create a connector. Then, use sql.OpenDB to create a connection pool and verify with db.Ping(). ```go cfg := pq.Config{ Host: "localhost", Port: 5432, User: "pqgo", } // Or: create a new Config from the defaults, environment, and DSN. // cfg, err := pq.NewConfig("host=postgres dbname=pqgo") // if err != nil { // log.Fatal(err) // } c, err := pq.NewConnectorConfig(cfg) if err != nil { log.Fatal(err) } // Create connection pool. db := sql.OpenDB(c) deferr db.Close() // Make sure it works. err = db.Ping() if err != nil { log.Fatal(err) } ``` -------------------------------- ### sql-migrate Configuration File Example (YAML) Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/rubenv/sql-migrate/README.md Defines database connection details and migration directory for different environments. ```yaml development: dialect: sqlite3 datasource: test.db dir: migrations/sqlite3 production: dialect: postgres datasource: dbname=myapp sslmode=disable dir: migrations/postgres table: migrations ``` -------------------------------- ### Get Security Groups by Space GUIDs Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/docs/08-policy-server-api.md Use this endpoint to retrieve security groups associated with specific space GUIDs, along with global security groups. Ensure you have the necessary client certificates for authentication. ```bash curl -s \ --cacert certs/ca.crt \ --cert certs/client.crt \ --key certs/client.key \ https://policy-server.service.cf.internal:4003/networking/v1/internal/security_groups?space_guids=5351a742-6704-46df-8de0-1a376adab65c,d5bbc5ed-886a-44e6-945d-67df1013fa16 ``` -------------------------------- ### GET /networking/v1/internal/security_groups Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/docs/08-policy-server-api.md Retrieves a list of security groups associated with the provided space GUIDs and global security groups. ```APIDOC ## GET /networking/v1/internal/security_groups ### Description Return security groups that are bound to provided space guids as well as global security groups. ### Method GET ### Endpoint /networking/v1/internal/security_groups ### Parameters #### Query Parameters - **space_guids** (string) - Required - Comma-separated list of space GUIDs to filter security groups. ### Response #### Success Response (200) - **next** (integer) - Pagination indicator. - **security_groups** (array) - List of security group objects. #### Response Example { "next": 0, "security_groups": [ { "guid": "b4669e65-e196-4c4d-8504-913e69d525bb", "name": "public_networks", "rules": "[{\"protocol\":\"all\",\"destination\":\"0.0.0.0-9.255.255.255\",\"ports\":\"\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false},...]", "staging_default": true, "running_default": true, "staging_space_guids": [], "running_space_guids": [] } ] } ``` -------------------------------- ### Create a Basic CLI App Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/codegangsta/cli/README.md A minimal Cloud Foundry CLI application that displays help text. This serves as a starting point for more complex applications. ```go package main import ( "os" "github.com/urfave/cli" ) func main() { cli.NewApp().Run(os.Args) } ``` -------------------------------- ### Security Group Configuration Example Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/docs/08-policy-server-api.md This JSON object represents a security group configuration, detailing its GUID, name, rules, and association with spaces for staging and running. ```json { "next": 0, "security_groups": [ { "guid": "b4669e65-e196-4c4d-8504-913e69d525bb", "name": "public_networks", "rules": "[{\"protocol\":\"all\",\"destination\":\"0.0.0.0-9.255.255.255\",\"ports\":\"\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false},{\"protocol\":\"all\",\"destination\":\"11.0.0.0-169.253.255.255\",\"ports\":\"\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false},{\"protocol\":\"all\",\"destination\":\"169.255.0.0-172.15.255.255\",\"ports\":\"\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false},{\"protocol\":\"all\",\"destination\":\"172.32.0.0-192.167.255.255\",\"ports\":\"\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false},{\"protocol\":\"all\",\"destination\":\"192.169.0.0-255.255.255.255\",\"ports\":\"\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false}]", "staging_default": true, "running_default": true, "staging_space_guids": [], "running_space_guids": [] }, { "guid": "cb2d7b6a-0d91-4f63-a69c-4ebcb5c683a3", "name": "dns", "rules": "[{\"protocol\":\"tcp\",\"destination\":\"0.0.0.0/0\",\"ports\":\"53\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false},{\"protocol\":\"udp\",\"destination\":\"0.0.0.0/0\",\"ports\":\"53\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false}]", "staging_default": true, "running_default": true, "staging_space_guids": [], "running_space_guids": [] }, { "guid": "c1654f71-ead9-4a16-bc7e-10835cfea7f1", "name": "security-group-1", "rules": "[{\"protocol\":\"icmp\",\"destination\":\"0.0.0.0/0\",\"ports\":\"\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false},{\"protocol\":\"tcp\",\"destination\":\"10.0.11.0/24\",\"ports\":\"80,443\",\"type\":0,\"code\":0,\"description\":\"Allow http and https traffic to ZoneA\",\"log\":true}]", "staging_default": false, "running_default": false, "staging_space_guids": [], "running_space_guids": [ "5351a742-6704-46df-8de0-1a376adab65c" ] }, { "guid": "e22dcb62-e310-4aae-b560-9692cc809277", "name": "security-group-2", "rules": "[{\"protocol\":\"icmp\",\"destination\":\"0.0.0.0/0\",\"ports\":\"\",\"type\":0,\"code\":0,\"description\":\"\",\"log\":false},{\"protocol\":\"tcp\",\"destination\":\"10.0.11.0/24\",\"ports\":\"80,443\",\"type\":0,\"code\":0,\"description\":\"Allow http and https traffic to ZoneA\",\"log\":true}]", "staging_default": false, "running_default": false, "staging_space_guids": [ "d5bbc5ed-886a-44e6-945d-67df1013fa16" ], "running_space_guids": [] } ] } ``` -------------------------------- ### Context Support Example Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/go-sql-driver/mysql/README.md Shows how to use `context.Context` with database operations to manage deadlines and cancellations. This is crucial for robust applications, especially in distributed systems. ```go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() rows, err := db.QueryContext(ctx, "SELECT * FROM users") ``` -------------------------------- ### Preview Documentation Changes Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/proxy/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Builds and serves the Ginkgo documentation locally using Jekyll. Requires Bundler to be installed. ```bash bundle && bundle exec jekyll serve ``` -------------------------------- ### Go Project Contribution Guide Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/montanaflynn/stats/README.md Instructions for contributing to the Go project, including forking, branching, making changes, testing, linting, and submitting pull requests. ```bash git tag v0.x.x git push origin v0.x.x ``` -------------------------------- ### Network Policy Server Tags Response Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/docs/03-troubleshooting.md Example JSON response from querying the Network Policy Server. It lists tags and their corresponding IDs, which can be used to map GBP IDs to application GUIDs. ```json { "tags": [ { "id": "f0782c6c-a2fe-4cad-a206-3970c57bb532", "tag": "0001" }, { "id": "0f2e3339-0d19-4e87-b381-030c3619bd6b", "tag": "0002" }, { "id": "1ee630fd-528a-4d80-97cd-dea170be759d", "tag": "0003" } ] } ``` -------------------------------- ### Executing Migrations with sqlx Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/rubenv/sql-migrate/README.md Demonstrates how to execute migrations when using the `sqlx` library. Dereference the `*sqlx.DB` to access the underlying `sql.DB` for the `migrate.Exec` function. ```go n, err := migrate.Exec(db.DB, "sqlite3", migrations, migrate.Up) // ^^^ <-- Here db is a *sqlx.DB, the db.DB field is the plain sql.DB if err != nil { // Handle errors! } ``` -------------------------------- ### sql-migrate Up Command Options Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/rubenv/sql-migrate/README.md Lists the available options for the 'up' command, which applies database migrations. ```bash $ sql-migrate up --help Usage: sql-migrate up [options] ... Migrates the database to the most recent version available. Options: -config=dbconfig.yml Configuration file to use. -env="development" Environment. -limit=0 Limit the number of migrations (0 = unlimited). -version Run migrate up to a specific version, eg: the version number of migration 1_initial.sql is 1. -dryrun Don't apply migrations, just print them. ``` -------------------------------- ### Basic Database Connection Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/go-sql-driver/mysql/README.md Import the driver and use the database/sql API to open a connection. Configure connection pool settings for optimal performance. ```go import ( "database/sql" time _ "github.com/go-sql-driver/mysql" ) // ... db, err := sql.Open("mysql", "user:password@/dbname") if err != nil { panic(err) } // See "Important settings" section. db.SetConnMaxLifetime(time.Minute * 3) db.SetMaxOpenConns(10) db.SetMaxIdleConns(10) ``` -------------------------------- ### Example Output for Lagerflags Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/code.cloudfoundry.org/lager/v3/lagerflags/README.md This is the expected output when running the example program with the --logLevel debug flag. ```text {"timestamp":"1464388983.540486336","source":"my-component","message":"my-component.starting","log_level":1,"data":{}} Current log level is debug ``` -------------------------------- ### sql-migrate CLI Help Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/rubenv/sql-migrate/README.md Displays the available commands for the sql-migrate CLI tool. ```bash $ sql-migrate --help usage: sql-migrate [--version] [--help] [] Available commands are: down Undo a database migration new Create a new migration redo Reapply the last migration status Show migration status up Migrates the database to the most recent version available ``` -------------------------------- ### Install StatHat Support Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/rcrowley/go-metrics/README.md Additional command to install the StatHat Go client library required for StatHat support. ```sh go get github.com/stathat/go ``` -------------------------------- ### Start PostgreSQL Cluster Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Command to start the PostgreSQL database cluster. This must be run whenever pgx tests are to be executed. ```bash postgres -D .testdb/$POSTGRESQL_DATA_DIR ``` -------------------------------- ### Install iproute2 and libmnl for VTEP Inspection Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/docs/03-troubleshooting.md Installs necessary packages for inspecting VXLAN tunnel endpoints (VTEP) on a Diego cell. ```bash curl -o /tmp/iproute2.deb -L http://mirrors.kernel.org/ubuntu/pool/main/i/iproute2/iproute2_4.3.0-1ubuntu3_amd64.deb curl -o /tmp/libmnl0.deb -L http://mirrors.kernel.org/ubuntu/pool/main/libm/libmnl/libmnl0_1.0.3-5_amd64.deb dpkg -i /tmp/*.deb ``` -------------------------------- ### Create and Use a Resource Pool in Go Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/jackc/puddle/v2/README.md Demonstrates creating a pool of net.Conn resources, acquiring one, writing data, and releasing it. Ensure the constructor and destructor functions are correctly defined for your resource type. ```go package main import ( "context" "log" "net" "github.com/jackc/puddle/v2" ) func main() { constructor := func(context.Context) (net.Conn, error) { return net.Dial("tcp", "127.0.0.1:8080") } destructor := func(value net.Conn) { value.Close() } maxPoolSize := int32(10) pool, err := puddle.NewPool(&puddle.Config[net.Conn]{Constructor: constructor, Destructor: destructor, MaxSize: maxPoolSize}) if err != nil { log.Fatal(err) } // Acquire resource from the pool. res, err := pool.Acquire(context.Background()) if err != nil { log.Fatal(err) } // Use resource. _, err = res.Value().Write([]byte{1}) if err != nil { log.Fatal(err) } // Release when done. res.Release() } ``` -------------------------------- ### Install jsontoml CLI Tool Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/pelletier/go-toml/README.md Install the 'jsontoml' command-line tool to convert JSON files to TOML. This can be helpful for migrating configurations. ```bash go install github.com/pelletier/go-toml/cmd/jsontoml jsontoml --help ``` -------------------------------- ### Install tomljson CLI Tool Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/registry/vendor/github.com/pelletier/go-toml/README.md Install the 'tomljson' command-line tool to convert TOML files to JSON. This is useful for interoperability or debugging. ```bash go install github.com/pelletier/go-toml/cmd/tomljson tomljson --help ``` -------------------------------- ### Initialize and Configure Lager Logger with Flags Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/code.cloudfoundry.org/lager/v3/lagerflags/README.md This example demonstrates how to initialize a lager logger using command-line flags for log level configuration. It shows adding flags, parsing them, creating a logger, and dynamically changing the minimum log level. ```golang 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") } ``` -------------------------------- ### Start Local godoc Server Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/montanaflynn/stats/README.md Starts the godoc server locally on port 4444. Use this to view documentation for the stats package. ```bash godoc -http=:4444 ``` -------------------------------- ### Ginkgo Spec Example Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/example-apps/tick/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 setting test durations. ```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)) }) }) ``` -------------------------------- ### Create and Use Network Namespace in Go Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/vishvananda/netns/README.md Demonstrates how to create a new network namespace, perform operations within it (like listing interfaces), and then switch back to the original namespace. This code must be run with root privileges. ```go package main import ( "fmt" "net" "runtime" "github.com/vishvananda/netns" ) func main() { // Lock the OS Thread so we don't accidentally switch namespaces runtime.LockOSThread() defer runtime.UnlockOSThread() // Save the current network namespace origns, _ := netns.Get() defer origns.Close() // Create a new network namespace newns, _ := netns.New() defer newns.Close() // Do something with the network namespace ifaces, _ := net.Interfaces() fmt.Printf("Interfaces: %v\n", ifaces) // Switch back to the original namespace netns.Set(origns) } ``` -------------------------------- ### Install Gomega Plugin for Claude Code Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/onsi/gomega/README.md Install the Gomega plugin for Claude Code to use Gomega's idioms within your test suite. This enables the full matcher catalog and sub-libraries. ```bash /plugin marketplace add onsi/gomega /plugin install gomega@gomega ``` ```bash claude plugin marketplace add onsi/gomega claude plugin install gomega@gomega ``` -------------------------------- ### DSN Examples for Go-MySQL-Driver Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/go-sql-driver/mysql/README.md Illustrates various Data Source Name (DSN) configurations for connecting to MySQL, covering different protocols, addresses, and parameters. Choose the DSN that best suits your connection requirements. ```go // DSN with TCP protocol // user:password@tcp(127.0.0.1:3306)/dbname?param=value // DSN with Unix socket // user:password@unix(/path/to/mysql.sock)/dbname?param=value ``` -------------------------------- ### Calculate Mean Source: https://github.com/cloudfoundry/cf-networking-release/blob/develop/src/code.cloudfoundry.org/vendor/github.com/montanaflynn/stats/DOCUMENTATION.md Gets the average of a slice of numbers. ```go func Mean(input Float64Data) (float64, error) ```