### Build and Run Goth Examples Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/markbates/goth/README.md Steps to get, build, and run the example application for Goth. Ensure you navigate to the examples directory and install dependencies. ```text cd goth/examples go get -v go build ./examples ``` -------------------------------- ### Basic Chi Router Setup Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/go-chi/chi/v5/README.md A simple example of initializing a Chi router, applying basic middleware, and defining a root GET route. This is a good starting point for any Chi application. ```go package main import ( "net/http" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" ) func main() { r := chi.NewRouter() r.Use(middleware.Logger) r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("welcome")) }) http.ListenAndServe(":3000", r) } ``` -------------------------------- ### Basic Chi Router Setup Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-chi/chi/README.md Demonstrates the simplest way to create a Chi router, define a GET route, and start an HTTP server. ```go package main import ( "net/http" "github.com/go-chi/chi" ) func main() { r := chi.NewRouter() r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("welcome")) }) http.ListenAndServe(":3000", r) } ``` -------------------------------- ### Basic Router Setup Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-chi/chi/README.md A simple example of initializing a Go-Chi router and defining a basic GET route. ```APIDOC ## Basic Router Setup ### Description This example shows how to create a new router instance and register a handler for the root path. ### Code ```go package main import ( "net/http" "github.com/go-chi/chi" ) func main() { r := chi.NewRouter() r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("welcome")) }) http.ListenAndServe(":3000", r) } ``` ``` -------------------------------- ### Installation Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/fogleman/gg/README.md Instructions on how to install the gg library using go get. ```APIDOC ## Installation ```go go get -u github.com/fogleman/gg ``` Alternatively, you may use gopkg.in to grab a specific major-version: ```go go get -u gopkg.in/fogleman/gg.v1 ``` ``` -------------------------------- ### Install goccy/go-json Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/goccy/go-json/README.md Use go get to install the library. This command fetches and installs the specified package. ```go go get github.com/goccy/go-json ``` -------------------------------- ### Install apitest-jsonpath Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/steinfletcher/apitest-jsonpath/README.md Use 'go get' to install the library. This command fetches and installs the specified package. ```bash go get -u github.com/steinfletcher/apitest-jsonpath ``` -------------------------------- ### Install Afero Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/spf13/afero/README.md Use 'go get' to install the Afero library. Then, import it into your Go application. ```bash go get github.com/spf13/afero ``` ```go import "github.com/spf13/afero" ``` -------------------------------- ### Install sqlx Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/jmoiron/sqlx/README.md Use 'go get' to install the sqlx library for your Go project. ```go go get github.com/jmoiron/sqlx ``` -------------------------------- ### Install Sonyflake Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/sony/sonyflake/README.md Use 'go get' to install the sonyflake package. ```go go get github.com/sony/sonyflake ``` -------------------------------- ### Sonyflake Installation Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/sony/sonyflake/README.md Instructions on how to install the Sonyflake library using go get. ```APIDOC ``` go get github.com/sony/sonyflake ``` ``` -------------------------------- ### Install go-sourcemap Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-sourcemap/sourcemap/README.md Use `go get` to install the latest version of the sourcemap library. ```shell go get -u github.com/go-sourcemap/sourcemap ``` -------------------------------- ### Install tiktoken-go Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/pkoukk/tiktoken-go/README.md Use 'go get' to install the tiktoken-go library. ```bash go get github.com/pkoukk/tiktoken-go ``` -------------------------------- ### Install cronexpr Library Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/gorhill/cronexpr/README.md Use 'go get' to install the cronexpr library. This command fetches and installs the package. ```bash go get github.com/gorhill/cronexpr ``` -------------------------------- ### Install GoDotEnv Library Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/joho/godotenv/README.md Use `go get` to install the GoDotEnv library for use in your Go projects. ```shell go get github.com/joho/godotenv ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/json-iterator/go/README.md Install the library using the go get command. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install copystructure Go Library Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/mitchellh/copystructure/README.md Use standard go get to install the library. This is the initial step before using its deep copying functionalities. ```bash $ go get github.com/mitchellh/copystructure ``` -------------------------------- ### Hello, Circle! Example Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/fogleman/gg/README.md A simple example demonstrating how to create a new context, draw a circle, set its color, fill it, and save the result as a PNG image. ```go package main import "github.com/fogleman/gg" func main() { dc := gg.NewContext(1000, 1000) dc.DrawCircle(500, 500, 400) dc.SetRGB(0, 0, 0) dc.Fill() dc.SavePNG("out.png") } ``` -------------------------------- ### Install Cobra Library Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/spf13/cobra/README.md Use 'go get' to install the latest version of the Cobra library. ```go go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Hello, Circle! Example Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/fogleman/gg/README.md A simple example demonstrating how to create a new context, draw a circle, set its color, fill it, and save it as a PNG image. ```APIDOC ## Hello, Circle! Look how easy! ```go package main import "github.com/fogleman/gg" func main() { dc := gg.NewContext(1000, 1000) dc.DrawCircle(500, 500, 400) dc.SetRGB(0, 0, 0) dc.Fill() dc.SavePNG("out.png") } ``` ``` -------------------------------- ### Install Mergo Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/imdario/mergo/README.md Use 'go get' to install the Mergo library. You will also need to import it into your Go code. ```go go get github.com/imdario/mergo // use in your .go code import ( "github.com/imdario/mergo" ) ``` -------------------------------- ### Install OAuth2 Server Package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-oauth2/oauth2/v4/README.md Download and install the OAuth2 server package using go get. ```bash go get -u -v github.com/go-oauth2/oauth2/v4/... ``` -------------------------------- ### Install Ubuntu Build Essentials Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/mattn/go-sqlite3/README.md Install the essential build tools for Ubuntu. ```bash sudo apt-get install build-essential ``` -------------------------------- ### Install go-sqlite3 Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/mattn/go-sqlite3/README.md Use the go get command to install the package. This is a CGO enabled package, so gcc must be present. ```go go get github.com/mattn/go-sqlite3 ``` -------------------------------- ### Install go-ini/ini Package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/gopkg.in/ini.v1/README.md Install the go-ini/ini package using the go get command. Use the -u flag for future updates. ```sh go get gopkg.in/ini.v1 ``` -------------------------------- ### Install OAuth2 Package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/go-oauth2/oauth2/v4/README.md Download and install the OAuth2 package using go get. ```bash go get -u -v github.com/go-oauth2/oauth2/v4/... ``` -------------------------------- ### Install Sentry Go SDK Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/getsentry/sentry-go/README.md Use 'go get' to install the Sentry Go SDK. Specify '@latest' for the most recent version. ```console go get github.com/getsentry/sentry-go ``` ```console go get github.com/getsentry/sentry-go@latest ``` -------------------------------- ### Install Gofakeit v6 Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/brianvoe/gofakeit/v6/README.md Use this command to install the Gofakeit v6 library. ```go go get github.com/brianvoe/gofakeit/v6 ``` -------------------------------- ### Install Mimetype Package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/gabriel-vasile/mimetype/README.md Use 'go get' to install the mimetype package. This command fetches and installs the package and its dependencies. ```bash go get github.com/gabriel-vasile/mimetype ``` -------------------------------- ### Install gorilla/mux Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/gorilla/mux/README.md Install the gorilla/mux package using the go get command. Ensure your Go toolchain is correctly configured. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Install apitest Go Package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/steinfletcher/apitest/README.md Use go get to install the apitest package. This command fetches and installs the latest version of the library. ```bash go get -u github.com/steinfletcher/apitest ``` -------------------------------- ### Install Go-MySQL-Driver Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-sql-driver/mysql/README.md Install the package 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 xstrings Go Package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/huandu/xstrings/README.md Use the go get command to install the xstrings library. This command fetches and installs the package, making it available for use in your Go projects. ```go go get github.com/huandu/xstrings ``` -------------------------------- ### Install gg Graphics Library Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/fogleman/gg/README.md Install the gg library using go get. Use gopkg.in for specific major versions. ```bash go get -u github.com/fogleman/gg ``` ```bash go get -u gopkg.in/fogleman/gg.v1 ``` -------------------------------- ### Install gorilla/csrf Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/gorilla/csrf/README.md Install the gorilla/csrf library using the Go toolchain. ```sh go get github.com/gorilla/csrf ``` -------------------------------- ### Install ctx package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/SentimensRG/ctx/README.md Use this command to install the ctx package. Ensure you are using Go 1.16 or later. ```bash go get -u github.com/SentimensRG/ctx ``` -------------------------------- ### System Variable Examples Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-sql-driver/mysql/README.md Examples of setting system variables like autocommit, time zone, and transaction isolation. Note the URL encoding for string values. ```text autocommit=1: SET autocommit=1 time_zone=%27Europe%2FParis%27: SET time_zone='Europe/Paris' transaction_isolation=%27REPEATABLE-READ%27: SET transaction_isolation='REPEATABLE-READ' ``` -------------------------------- ### Quickstart: Parse a Source Map Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-sourcemap/sourcemap/README.md Demonstrates how to fetch, parse a source map from a URL, and then retrieve original source file information for a given generated line and column. ```go func ExampleParse() { mapURL := "http://code.jquery.com/jquery-2.0.3.min.map" resp, err := http.Get(mapURL) if err != nil { panic(err) } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } smap, err := sourcemap.Parse(mapURL, b) if err != nil { panic(err) } line, column := 5, 6789 file, fn, line, col, ok := smap.Source(line, column) fmt.Println(file, fn, line, col, ok) // Output: http://code.jquery.com/jquery-2.0.3.js apply 4360 27 true } ``` -------------------------------- ### Full Example of a Mux-based Server Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/gorilla/mux/README.md Provides a complete, runnable Go program demonstrating a basic web server using Gorilla Mux. It includes setting up a router and handling a simple root path request. ```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)) } ``` -------------------------------- ### Go Development Dependencies and Commands Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/microcosm-cc/bluemonday/README.md Instructions for setting up the development environment for Bluemonday. This includes fetching dependencies and common build/test commands. ```bash go get golang.org/x/net/html ``` ```bash go build ``` ```bash go test ``` ```bash make ``` ```bash make clean ``` ```bash make test ``` ```bash make cover ``` ```bash make lint ``` -------------------------------- ### Install goxmldsig Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/russellhaering/goxmldsig/README.md Install the goxmldsig library using the go get command. ```bash $ go get github.com/russellhaering/goxmldsig ``` -------------------------------- ### Build and Run Server Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/go-oauth2/oauth2/v4/README.md Compile the Go server file and then run the executable. ```bash go build server.go ./server ``` -------------------------------- ### Install govalidator Package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/asaskevich/govalidator/README.md Use 'go get' to install the govalidator package. You can install the latest release or a specific version using gopkg.in. ```bash go get github.com/asaskevich/govalidator ``` ```bash go get gopkg.in/asaskevich/govalidator.v10 ``` -------------------------------- ### Basic Database Connection Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-sql-driver/mysql/README.md Import the driver and use sql.Open with 'mysql' as the driver name and a DSN. Configure connection pool settings for optimal performance and reliability. ```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) ``` -------------------------------- ### Install Sentry Go HTTP Handler Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/getsentry/sentry-go/http/README.md Install the sentry-go/http package using go get. ```sh go get github.com/getsentry/sentry-go/http ``` -------------------------------- ### Create and Use MD5 Hasher in Go Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/minio/md5-simd/README.md Demonstrates the basic usage of the md5-simd package: creating a server, instantiating a hasher, writing data, and retrieving the digest. Remember to close the server and hasher when no longer needed. ```go // Create server server := md5simd.NewServer() defer server.Close() // Create hashing object (conforming to hash.Hash) md5Hash := server.NewHash() defer md5Hash.Close() // Write one (or more) blocks md5Hash.Write(block) // Return digest digest := md5Hash.Sum([]byte{}) ``` -------------------------------- ### Create OAuth2 Server Instance Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-oauth2/oauth2/v4/README.md Set up a new OAuth2 server instance with token and client storage. This example uses in-memory stores and configures handlers for authorization and token requests. ```go package main import ( "log" "net/http" "github.com/go-oauth2/oauth2/v4/errors" "github.com/go-oauth2/oauth2/v4/manage" "github.com/go-oauth2/oauth2/v4/models" "github.com/go-oauth2/oauth2/v4/server" "github.com/go-oauth2/oauth2/v4/store" ) func main() { manager := manage.NewDefaultManager() // token memory store manager.MustTokenStorage(store.NewMemoryTokenStore()) // client memory store clientStore := store.NewClientStore() clientStore.Set("000000", &models.Client{ ID: "000000", Secret: "999999", Domain: "http://localhost", }) manager.MapClientStorage(clientStore) srv := server.NewDefaultServer(manager) srv.SetAllowGetAccessRequest(true) srv.SetClientInfoHandler(server.ClientFormHandler) srv.SetInternalErrorHandler(func(err error) (re *errors.Response) { log.Println("Internal Error:", err.Error()) return }) srv.SetResponseErrorHandler(func(re *errors.Response) { log.Println("Response Error:", re.Error.Error()) }) http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) { err := srv.HandleAuthorizeRequest(w, r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } }) http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { srv.HandleTokenRequest(w, r) }) log.Fatal(http.ListenAndServe(":9096", nil)) } ``` -------------------------------- ### File Uploader Example Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/minio/minio-go/v6/README.md This Go program connects to MinIO, creates a bucket, and uploads a file. It handles potential errors like the bucket already existing. ```go package main import ( "github.com/minio/minio-go/v6" "log" ) func main() { endpoint := "play.min.io" accessKeyID := "Q3AM3UQ867SPQQA43P2F" secretAccessKey := "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG" useSSL := true // Initialize minio client object. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL) if err != nil { log.Fatalln(err) } // Make a new bucket called mymusic. bucketName := "mymusic" location := "us-east-1" err = minioClient.MakeBucket(bucketName, location) if err != nil { // Check to see if we already own this bucket (which happens if you run this twice) exists, errBucketExists := minioClient.BucketExists(bucketName) if errBucketExists == nil && exists { log.Printf("We already own %s\n", bucketName) } else { log.Fatalln(err) } } else { log.Printf("Successfully created %s\n", bucketName) } // Upload the zip file objectName := "golden-oldies.zip" filePath := "/tmp/golden-oldies.zip" contentType := "application/zip" // Upload the zip file with FPutObject n, err := minioClient.FPutObject(bucketName, objectName, filePath, minio.PutObjectOptions{ContentType:contentType}) if err != nil { log.Fatalln(err) } log.Printf("Successfully uploaded %s of size %d\n", objectName, n) } ``` -------------------------------- ### Install go.uber.org/atomic Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/go.uber.org/atomic/README.md Install the atomic package using go get. Ensure you are using the latest version for module support. ```shell go get -u go.uber.org/atomic@v1 ``` -------------------------------- ### Migrating to Go Modules (Initialization) Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/lestrrat-go/backoff/v2/README.md Instructions for initializing Go Modules in a project to resolve GOPATH-related issues with external packages. ```bash git clone git@github.com:myusername/myawesomeproject.git cd myawesomeproject go mod init go mod tidy git add go.mod go.sum git commit -m "Add go.mod and go.sum" ``` -------------------------------- ### Get App Engine Go SDK Package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/google.golang.org/appengine/CONTRIBUTING.md Use 'go get -d' to download the App Engine Go SDK package. This command fetches the source code without installing it, preparing it for development. ```bash go get -d google.golang.org/appengine ``` -------------------------------- ### Comprehensive Image Manipulation Example in Go Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/disintegration/imaging/README.md This example demonstrates a full workflow of image manipulation using the imaging library, including opening, cropping, resizing, blurring, converting to grayscale, inverting, applying a convolution filter, and saving the final image. ```go package main import ( "image" "image/color" "log" "github.com/disintegration/imaging" ) func main() { // Open a test image. src, err := imaging.Open("testdata/flowers.png") if err != nil { log.Fatalf("failed to open image: %v", err) } // Crop the original image to 300x300px size using the center anchor. src = imaging.CropAnchor(src, 300, 300, imaging.Center) // Resize the cropped image to width = 200px preserving the aspect ratio. src = imaging.Resize(src, 200, 0, imaging.Lanczos) // Create a blurred version of the image. img1 := imaging.Blur(src, 5) // Create a grayscale version of the image with higher contrast and sharpness. img2 := imaging.Grayscale(src) img2 = imaging.AdjustContrast(img2, 20) img2 = imaging.Sharpen(img2, 2) // Create an inverted version of the image. img3 := imaging.Invert(src) // Create an embossed version of the image using a convolution filter. img4 := imaging.Convolve3x3( src, [9]float64{ -1, -1, 0, -1, 1, 1, 0, 1, 1, }, nil, ) // Create a new image and paste the four produced images into it. dst := imaging.New(400, 400, color.NRGBA{0, 0, 0, 0}) dst = imaging.Paste(dst, img1, image.Pt(0, 0)) dst = imaging.Paste(dst, img2, image.Pt(0, 200)) dst = imaging.Paste(dst, img3, image.Pt(200, 0)) dst = imaging.Paste(dst, img4, image.Pt(200, 200)) // Save the resulting image as JPEG. err = imaging.Save(dst, "testdata/out_example.jpg") if err != nil { log.Fatalf("failed to save image: %v", err) } } ``` -------------------------------- ### Install Zapfilter using Go Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/moul.io/zapfilter/README.md Use this command to get the latest version of the Zapfilter library for your Go project. ```console $ go get -u moul.io/zapfilter ``` -------------------------------- ### Reinstall go-sqlite3 Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/mattn/go-sqlite3/README.md If 'go get' fails with a gcc internal compiler error, remove the repository and use 'go install' instead. ```bash go install github.com/mattn/go-sqlite3 ``` -------------------------------- ### Run FileUploader Example Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/minio/minio-go/v6/README.md Commands to run the file uploader Go program and verify the upload using the MinIO client command-line tool. ```sh go run file-uploader.go 2016/08/13 17:03:28 Successfully created mymusic 2016/08/13 17:03:40 Successfully uploaded golden-oldies.zip of size 16253413 mc ls play/mymusic/ [2016-05-27 16:02:16 PDT] 17MiB golden-oldies.zip ``` -------------------------------- ### Node Interface Definition Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/dop251/goja/ast/README.markdown Defines the Node interface, which all AST nodes implement. It provides methods to get the start and end indices of a node in the source code. ```go type Node interface { Idx0() file.Idx // The index of the first character belonging to the node Idx1() file.Idx // The index of the first character immediately after the node } ``` -------------------------------- ### Simple Gofakeit Usage Examples Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/brianvoe/gofakeit/v6/README.md Demonstrates basic usage of Gofakeit functions to generate various types of random data. No special setup is required for these calls. ```go import "github.com/brianvoe/gofakeit/v6" gofakeit.Name() // Markus Moen gofakeit.Email() // alaynawuckert@kozey.biz gofakeit.Phone() // (570)245-7485 gofakeit.BS() // front-end gofakeit.BeerName() // Duvel gofakeit.Color() // MediumOrchid gofakeit.Company() // Moen, Pagac and Wuckert gofakeit.CreditCardNumber() // 4287271570245748 gofakeit.HackerPhrase() // Connecting the array won't do anything, we need to generate the haptic COM driver! gofakeit.JobTitle() // Director gofakeit.CurrencyShort() // USD ``` -------------------------------- ### Get JSON Representation of a Key Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/lestrrat-go/jwx/jwk/README.md This example demonstrates how to marshal a JWK key into its JSON representation using json.MarshalIndent. It includes generating an ECDSA key, setting a Key ID, and then marshaling it. ```go func ExampleMarshalJSON() { // to get the same values every time, we need to create a static source // of "randomness" rdr := bytes.NewReader([]byte("01234567890123456789012345678901234567890123456789ABCDEF")) raw, err := ecdsa.GenerateKey(elliptic.P384(), rdr) if err != nil { fmt.Printf("failed to generate new ECDSA privatre key: %s\n", err) return } key, err := jwk.New(raw) if err != nil { fmt.Printf("failed to create symmetric key: %s\n", err) return } if _, ok := key.(jwk.ECDSAPrivateKey); !ok { fmt.Printf("expected jwk.SymmetricKey, got %T\n", key) return } key.Set(jwk.KeyIDKey, "mykey") buf, err := json.MarshalIndent(key, "", " ") if err != nil { fmt.Printf("failed to marshal key into JSON: %s\n", err) return } fmt.Printf("%s\n", buf) // OUTPUT: // { // "kty": "EC", // "crv": "P-384", // "d": "ODkwMTIzNDU2Nzg5MDEyMz7deMbyLt8g4cjcxozuIoygLLlAeoQ1AfM9TSvxkFHJ", // "kid": "mykey", // "x": "gvvRMqm1w5aHn7sVNA2QUJeOVcedUnmiug6VhU834gzS9k87crVwu9dz7uLOdoQl", // "y": "7fVF7b6J_6_g6Wu9RuJw8geWxEi5ja9Gp2TSdELm5u2E-M7IF-bsxqcdOj3n1n7N" // } } ``` -------------------------------- ### Testing a Simple HTTP Handler with Mux Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/gorilla/mux/README.md Demonstrates how to test a basic HTTP handler function using Go's net/http/httptest package. This setup is useful for verifying handler logic without starting a full server. ```go // endpoints.go package main import ( "io" "log" "net/http" "github.com/gorilla/mux" ) func HealthCheckHandler(w http.ResponseWriter, r *http.Request) { // A very simple health check. w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) // In the future we could report back on the status of our DB, or our cache // (e.g. Redis) by performing a simple PING, and include them in the response. io.WriteString(w, `{"alive": true}`) } func main() { r := mux.NewRouter() r.HandleFunc("/health", HealthCheckHandler) log.Fatal(http.ListenAndServe("localhost:8080", r)) } ``` ```go // endpoints_test.go package main import ( "net/http" "net/http/httptest" "testing" ) func TestHealthCheckHandler(t *testing.T) { // Create a request to pass to our handler. We don't have any query parameters for now, so we'll // pass 'nil' as the third parameter. req, err := http.NewRequest("GET", "/health", nil) if err != nil { t.Fatal(err) } // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. rr := httptest.NewRecorder() handler := http.HandlerFunc(HealthCheckHandler) // Our handlers satisfy http.Handler, so we can call their ServeHTTP method // directly and pass in our Request and ResponseRecorder. handler.ServeHTTP(rr, req) // Check the status code is what we expect. if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"alive": true}` if rr.Body.String() != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } } ``` -------------------------------- ### Migrating to Go Modules (Post-Initialization) Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/lestrrat-go/backoff/v2/README.md After initializing Go Modules, this command builds or runs your project, respecting the go.mod file for dependency management. ```bash git clone git@github.com:myusername/myawesomeproject.git cd myawesomeproject go build # or go test, or go run, or whatever. ``` -------------------------------- ### Install uuid Package Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/google/uuid/README.md Use this command to install the uuid package. Ensure you have Go installed and configured. ```sh go get github.com/google/uuid ``` -------------------------------- ### Run Benchmarks Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/goccy/go-json/README.md Navigate to the benchmarks directory and run the go test command with the -bench flag to execute performance benchmarks. ```bash $ cd benchmarks $ go test -bench . ``` -------------------------------- ### Install Compute Metadata Library Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/cloud.google.com/go/compute/metadata/README.md Use this command to install the Google Cloud Compute metadata Go library. Ensure you have Go installed and configured. ```bash go get cloud.google.com/go/compute/metadata ``` -------------------------------- ### LOAD DATA LOCAL INFILE Support Setup Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/go-sql-driver/mysql/README.md Enable LOAD DATA LOCAL INFILE support by changing the import path and either registering specific files or disabling the check with 'allowAllFiles=true'. ```go import "github.com/go-sql-driver/mysql" ``` -------------------------------- ### Install SQLite3 on macOS Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/mattn/go-sqlite3/README.md Use Homebrew to install the sqlite3 dependency on macOS. ```bash brew install sqlite3 ``` -------------------------------- ### Prepare Release with Craft Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/getsentry/sentry-go/CONTRIBUTING.md Use the 'craft' tool to prepare a new release version. ```console $ craft prepare X.X.X ``` -------------------------------- ### Parse and Use JWK Key Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/extra/server-discovery/vendor/github.com/lestrrat-go/jwx/jwk/README.md This example shows how to fetch a JWK set from a URL, serialize it to JSON, iterate through the keys, and extract the raw key material. It also demonstrates creating a jwk.Key from raw material and parsing JSON back into a jwk.Key. ```go import ( "encoding/json" "log" "github.com/lestrrat-go/jwx/jwk" ) func main() { set, err := jwk.Fetch(context.Background(), "https://www.googleapis.com/oauth2/v3/certs") if err != nil { log.Printf("failed to parse JWK: %s", err) return } // Key sets can be serialized back to JSON { jsonbuf, err := json.Marshal(set) if err != nil { log.Printf("failed to marshal key set into JSON: %s", err) return } log.Printf("%s", jsonbuf) } for it := set.Iterate(context.Background()); it.Next(context.Background()); { pair := it.Pair() key := pair.Value.(jwk.Key) var rawkey interface{} // This is the raw key, like *rsa.PrivateKey or *ecdsa.PrivateKey if err := key.Raw(&rawkey); err != nil { log.Printf("failed to create public key: %s", err) return } // Use rawkey for jws.Verify() or whatever. _ = rawkey // You can create jwk.Key from a raw key, too fromRawKey, err := jwk.New(rawkey) // Keys can be serialized back to JSON jsonbuf, err := json.Marshal(key) if err != nil { log.Printf("failed to marshal key into JSON: %s", err) return } log.Printf("%s", jsonbuf) // If you know the underlying Key type (RSA, EC, Symmetric), you can // create an empy instance first // key := jwk.NewRSAPrivateKey() // ..and then use json.Unmarshal // json.Unmarshal(key, jsonbuf) // // but if you don't know the type first, you have an abstract type // jwk.Key, which can't be used as the first argument to json.Unmarshal // // In this case, use jwk.Parse() fromJsonKey, err := jwk.Parse(jsonbuf) if err != nil { log.Printf("failed to parse json: %s", err) return } _ = fromJsonKey _ = fromRawKey } } ``` -------------------------------- ### Install go-fuzz Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/valyala/fastjson/README.md Installs the go-fuzz tool and go-fuzz-build. These are required for fuzzing Go programs. ```bash go get -u github.com/dvyukov/go-fuzz/go-fuzz github.com/dvyukov/go-fuzz/go-fuzz-build ``` -------------------------------- ### Install Fedora Development Tools Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/mattn/go-sqlite3/README.md Install the required development tools and libraries for Fedora. ```bash sudo yum groupinstall "Development Tools" "Development Libraries" ``` -------------------------------- ### Install Alpine Dependencies Source: https://github.com/cortezaproject/corteza/blob/2024.9.x/server/vendor/github.com/mattn/go-sqlite3/README.md Before building in an Alpine container, install necessary development tools. ```bash apk add --update gcc musl-dev ```