### Basic Gin Application Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gin-gonic/gin/README.md A simple 'Hello World' example demonstrating how to create a Gin router, define a GET route for '/ping', and start the server. This code listens on 0.0.0.0:8080. ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") } ``` -------------------------------- ### Install goccy/go-json Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/goccy/go-json/README.md Use 'go get' to install the library. This command fetches and installs the specified package and its dependencies. ```bash go get github.com/goccy/go-json ``` -------------------------------- ### Install go-playground/locales Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/go-playground/locales/README.md Use 'go get' to install the locales library. ```shell go get github.com/go-playground/locales ``` -------------------------------- ### Install Locafero Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/sagikazarmark/locafero/README.md Use this command to install the Locafero library using go get. ```shell go get github.com/sagikazarmark/locafero ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/mattn/go-isatty/README.md Install the go-isatty package using the go get command. ```bash go get github.com/mattn/go-isatty ``` -------------------------------- ### Basic Mux Server Setup Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gorilla/mux/README.md A complete, runnable example of a minimal HTTP server using Gorilla Mux, demonstrating basic route registration and server startup. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Install Cobra Library Source: https://github.com/nhost/hasura-storage/blob/main/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 ``` -------------------------------- ### Install Mimetype Package Source: https://github.com/nhost/hasura-storage/blob/main/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 Afero Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/spf13/afero/README.md Install the latest version of Afero using go get. Include it in your application by importing the package. ```bash $ go get github.com/spf13/afero ``` ```go import "github.com/spf13/afero" ``` -------------------------------- ### Install gorilla/mux Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gorilla/mux/README.md Use go get to install the gorilla/mux package. Ensure your Go toolchain is correctly configured. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/apapsch/go-jsonmerge/v2/README.md Commands to set up development environment by installing dependencies and building the project using provided shell scripts. ```bash # Install depencencies ./init.sh # Build ./build.sh ``` -------------------------------- ### Install YAML Package for Go Source: https://github.com/nhost/hasura-storage/blob/main/vendor/gopkg.in/yaml.v2/README.md Use 'go get' to install the yaml package. This command fetches and installs the specified package and its dependencies. ```bash go get gopkg.in/yaml.v2 ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/json-iterator/go/README.md Use the go get command to install the json-iterator/go library into your project. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install multierr Source: https://github.com/nhost/hasura-storage/blob/main/vendor/go.uber.org/multierr/README.md Install the latest version of the multierr package using go get. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Install Viper using Go Modules Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/spf13/viper/README.md Install the Viper library using the go get command. Viper utilizes Go Modules for dependency management. ```shell go get github.com/spf13/viper ``` -------------------------------- ### Start Hasura Storage Server Source: https://context7.com/nhost/hasura-storage/llms.txt Starts the Hasura Storage HTTP server with MinIO and local Hasura configuration. This example includes optional antivirus scanning. ```bash hasura-storage serve \ --public-url "http://localhost:8000" \ --api-root-prefix "/v1" \ --bind ":8000" \ --hasura-endpoint "http://localhost:8080/v1" \ --hasura-graphql-admin-secret "nhost-admin-secret" \ --s3-endpoint "http://localhost:9000" \ --s3-access-key "minioadmin" \ --s3-secret-key "minioadmin" \ --s3-region "us-east-1" \ --s3-bucket "default" \ --s3-root-folder "f215cf48-7458-4596-9aa5-2159fc6a3caf" \ --postgres-migrations \ --postgres-migrations-source "postgres://postgres:password@localhost:5432/postgres?sslmode=disable" \ --hasura-metadata \ --cors-allow-origins "*" \ --clamav-server "tcp://clamavd:3310" # optional antivirus ``` ```yaml # Equivalent YAML config (hasura-storage.yaml): # debug: true # hasura-endpoint: http://localhost:8080/v1 # hasura-metadata: true # hasura-graphql-admin-secret: nhost-admin-secret # s3-endpoint: "http://localhost:9000" # s3-access-key: "minioadmin" # s3-secret-key: "minioadmin" # s3-disable-http: true # s3-region: "us-east-1" # s3-bucket: "default" # s3-root-folder: "f215cf48-7458-4596-9aa5-2159fc6a3caf" # postgres-migrations: true # postgres-migrations-source: postgres://postgres:password@localhost:5432/postgres ``` ```bash go run main.go serve # or: nix run . -- serve ``` -------------------------------- ### Install Universal Translator Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/go-playground/universal-translator/README.md Use 'go get' to install the Universal Translator package. ```shell go get github.com/go-playground/universal-translator ``` -------------------------------- ### Start Development Environment Containers Source: https://github.com/nhost/hasura-storage/blob/main/DEVELOPMENT.md Starts the necessary Docker containers for local development. ```bash make dev-env-up-short ``` -------------------------------- ### Install jsontoml tool Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/pelletier/go-toml/v2/README.md Install the jsontoml command-line tool. Use 'go install' with the '@latest' tag to get the most recent version. Run '--help' for usage information. ```bash go install github.com/pelletier/go-toml/v2/cmd/jsontoml@latest jsontoml --help ``` -------------------------------- ### Install go-yaml/yaml v3 Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/oasdiff/yaml3/README.md Use 'go get' to install the latest version of the yaml package for your Go projects. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Install go-urn Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/leodido/go-urn/README.md Use this command to install the go-urn library. It is compatible with Go modules. ```go go get github.com/leodido/go-urn ``` -------------------------------- ### Install tomljson tool Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/pelletier/go-toml/v2/README.md Install the tomljson command-line tool. Use 'go install' with the '@latest' tag to get the most recent version. Run '--help' for usage information. ```bash go install github.com/pelletier/go-toml/v2/cmd/tomljson@latest tomljson --help ``` -------------------------------- ### Install Uber Atomic Package Source: https://github.com/nhost/hasura-storage/blob/main/vendor/go.uber.org/atomic/README.md Use 'go get' to install the latest version of the atomic package. ```shell $ go get -u go.uber.org/atomic@v1 ``` -------------------------------- ### Install Marshmallow Go Package Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/perimeterx/marshmallow/README.md Use 'go get' to install the Marshmallow package. This command fetches and installs the latest version. ```sh go get -u github.com/perimeterx/marshmallow ``` -------------------------------- ### Install Go Struct Validator Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/go-playground/validator/v10/README.md Use go get to install the validator package. Then import it into your Go code. ```go go get github.com/go-playground/validator/v10 ``` ```go import "github.com/go-playground/validator/v10" ``` -------------------------------- ### Install mapstructure v2 Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/go-viper/mapstructure/v2/README.md Use `go get` to install the latest version of the mapstructure library. ```shell go get github.com/go-viper/mapstructure/v2 ``` -------------------------------- ### Run Gin Example Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gin-gonic/gin/README.md Command to execute a Go file containing a Gin application. Access the defined routes via the specified port. ```sh # run example.go and visit 0.0.0.0:8080/ping on browser $ go run example.go ``` -------------------------------- ### Install Gin Package Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gin-gonic/gin/README.md Use this command to install the Gin package if you are not using Go modules. ```sh $ go get -u github.com/gin-gonic/gin ``` -------------------------------- ### Get Configuration Values with Viper Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/spf13/viper/README.md Demonstrates how to retrieve configuration values of various types using Viper's Get methods. It also shows how to check if a key is set using IsSet, and explains that Get methods return zero values if a key is not found or fails to parse. ```go viper.GetString("logfile") // case-insensitive Setting & Getting if viper.GetBool("verbose") { fmt.Println("verbose enabled") } ``` -------------------------------- ### Install jwt-go Package Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/golang-jwt/jwt/v5/README.md Install the jwt-go package using the go get command. This adds the library as a dependency to your Go program. ```sh go get -u github.com/golang-jwt/jwt/v5 ``` -------------------------------- ### Run hasura-storage Serve with Nix Source: https://github.com/nhost/hasura-storage/blob/main/DEVELOPMENT.md Starts the hasura-storage server using Nix. This is an alternative to the `go run` command when using the Nix development environment. ```bash nix run . -- serve ``` -------------------------------- ### Install and Use jsonmerge Commandline Tool Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/apapsch/go-jsonmerge/v2/README.md Instructions for installing the jsonmerge command-line tool and its basic usage pattern for merging JSON files. Use the -h flag for detailed help. ```bash $ go get -u github.com/RaveNoX/go-jsonmerge/cmd/jsonmerge $ jsonmerge [options] ... # For help $ jsonmerge -h ``` -------------------------------- ### TOML with Comments Example Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/pelletier/go-toml/v2/README.md Illustrates how go-toml can emit TOML documents with comments and commented-out values, useful for configuration files. ```toml # Host IP to connect to. host = '127.0.0.1' # Port of the remote server. port = 4242 # Encryption parameters (optional) # [TLS] # cipher = 'AEAD-AES128-GCM-SHA256' # version = 'TLS 1.3' ``` -------------------------------- ### Basic JSON Encoding Example Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/goccy/go-json/README.md Demonstrates a typical use case for marshaling a simple struct into JSON. ```go json.Marshal(struct{ X int `json:"x"` Y string `json:"y"` }{X: 1, Y: "hello"}) ``` -------------------------------- ### Run hasura-storage Serve Command Source: https://github.com/nhost/hasura-storage/blob/main/DEVELOPMENT.md Starts the hasura-storage server. This command is an alternative to `make dev-env-up-hasura` if the development environment is correctly configured. ```bash go run main.go serve ``` -------------------------------- ### Run Linter Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/golang-migrate/migrate/v4/CONTRIBUTING.md Execute the golangci-lint linter to check code quality. Ensure golangci-lint is installed first. ```bash golangci-lint run ``` -------------------------------- ### Marshalling Viper Settings to YAML String Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/spf13/viper/README.md Use `AllSettings()` to get all configuration values and then marshal them into a string format like YAML using an external library. ```go import ( yaml "gopkg.in/yaml.v2" // ... ) func yamlStringSettings() string { c := viper.AllSettings() bs, err := yaml.Marshal(c) if err != nil { log.Fatalf("unable to marshal config to YAML: %v", err) } return string(bs) } ``` -------------------------------- ### Initializing Operating System Filesystem Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/spf13/afero/README.md Demonstrates how to initialize Afero's OsFs, which wraps native OS calls. This is useful for using the actual filesystem during operation or for integration tests. ```go appfs := afero.NewOsFs() appfs.MkdirAll("src/a", 0755) ``` -------------------------------- ### Implement RPC Server Codec Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/ugorji/go/codec/README.md Illustrates how to set up an RPC server using the go-codec package. It shows accepting incoming connections and creating a server codec for either the standard Go RPC or MsgpackSpec RPC. ```go //RPC Server go func() { for { conn, err := listener.Accept() rpcCodec := codec.GoRpc.ServerCodec(conn, h) //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h) rpc.ServeCodec(rpcCodec) } }() ``` -------------------------------- ### Initialize and Configure Handle for Encoding/Decoding Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/ugorji/go/codec/README.md Demonstrates the creation and configuration of different Handle types (Binc, Msgpack, Cbor) and setting up custom extensions for types like time.Time. This setup is done before any encoding or decoding operations. ```go // create and configure Handle var ( bh codec.BincHandle mh codec.MsgpackHandle ch codec.CborHandle ) mh.MapType = reflect.TypeOf(map[string]interface{}(nil)) // configure extensions // e.g. for msgpack, define functions and enable Time support for tag 1 // mh.SetExt(reflect.TypeOf(time.Time{}), 1, myExt) ``` -------------------------------- ### Basic Test Script Example Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Illustrates the basic syntax for creating test cases using a shell-like script format. Includes creating a file and observing the expected output events. ```bash # Create a new empty file with some data. watch / echo data >/file Output: create /file write /file ``` -------------------------------- ### Install Gin CORS Middleware Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gin-contrib/cors/README.md Download and install the gin-contrib/cors package using go get. ```sh go get github.com/gin-contrib/cors ``` -------------------------------- ### Build URL with Host, Path, and Query Variables Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gorilla/mux/README.md Define a route with host, path, and query variables, then build the complete URL. This example includes subdomain, category, ID, and a filter query parameter. ```go r := mux.NewRouter() r.Host("{subdomain}.example.com"). Path("/articles/{category}/{id:[0-9]+}"). Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article") // url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42", "filter", "gorilla") ``` -------------------------------- ### Initializing Memory-Backed Filesystem Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/spf13/afero/README.md Shows how to initialize Afero's MemMapFs, an atomic and concurrent in-memory filesystem. This is ideal for mocking and speeding up tests by avoiding disk I/O. ```go mm := afero.NewMemMapFs() mm.MkdirAll("src/a", 0755) ``` -------------------------------- ### Run Benchmarks Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/goccy/go-json/README.md Navigate to the benchmarks directory and run the Go tests with the -bench flag to measure performance. ```bash cd benchmarks go test -bench . ``` -------------------------------- ### Create and Use Decoder/Encoder Instances Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/ugorji/go/codec/README.md Shows how to create Decoder and Encoder instances using various sources (io.Reader, []byte) and destinations (io.Writer, *[]byte) with a pre-configured Handle. Includes basic Decode and Encode operations. ```go // create and use decoder/encoder var ( r io.Reader w io.Writer b []byte h = &bh // or mh to use msgpack ) dec = codec.NewDecoder(r, h) dec = codec.NewDecoderBytes(b, h) err = dec.Decode(&v) enc = codec.NewEncoder(w, h) enc = codec.NewEncoderBytes(&b, h) err = enc.Encode(v) ``` -------------------------------- ### Install tomll tool Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/pelletier/go-toml/v2/README.md Install the tomll command-line tool for linting and reformatting TOML files. Use 'go install' with the '@latest' tag to get the most recent version. Run '--help' for usage information. ```bash go install github.com/pelletier/go-toml/v2/cmd/tomll@latest tomll --help ``` -------------------------------- ### Basic Locale Usage and Formatting Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/go-playground/locales/README.md Demonstrates how to initialize a locale (e.g., en_CA) and use it for formatting dates, times, numbers, currencies, and percentages. It also shows how to retrieve pluralization rules. ```go package main import ( "fmt" "time" "github.com/go-playground/locales/currency" "github.com/go-playground/locales/en_CA" ) func main() { loc, _ := time.LoadLocation("America/Toronto") datetime := time.Date(2016, 02, 03, 9, 0, 1, 0, loc) l := en_CA.New() // Dates fmt.Println(l.FmtDateFull(datetime)) fmt.Println(l.FmtDateLong(datetime)) fmt.Println(l.FmtDateMedium(datetime)) fmt.Println(l.FmtDateShort(datetime)) // Times fmt.Println(l.FmtTimeFull(datetime)) fmt.Println(l.FmtTimeLong(datetime)) fmt.Println(l.FmtTimeMedium(datetime)) fmt.Println(l.FmtTimeShort(datetime)) // Months Wide fmt.Println(l.MonthWide(time.January)) fmt.Println(l.MonthWide(time.February)) fmt.Println(l.MonthWide(time.March)) // ... // Months Abbreviated fmt.Println(l.MonthAbbreviated(time.January)) fmt.Println(l.MonthAbbreviated(time.February)) fmt.Println(l.MonthAbbreviated(time.March)) // ... // Months Narrow fmt.Println(l.MonthNarrow(time.January)) fmt.Println(l.MonthNarrow(time.February)) fmt.Println(l.MonthNarrow(time.March)) // ... // Weekdays Wide fmt.Println(l.WeekdayWide(time.Sunday)) fmt.Println(l.WeekdayWide(time.Monday)) fmt.Println(l.WeekdayWide(time.Tuesday)) // ... // Weekdays Abbreviated fmt.Println(l.WeekdayAbbreviated(time.Sunday)) fmt.Println(l.WeekdayAbbreviated(time.Monday)) fmt.Println(l.WeekdayAbbreviated(time.Tuesday)) // ... // Weekdays Short fmt.Println(l.WeekdayShort(time.Sunday)) fmt.Println(l.WeekdayShort(time.Monday)) fmt.Println(l.WeekdayShort(time.Tuesday)) // ... // Weekdays Narrow fmt.Println(l.WeekdayNarrow(time.Sunday)) fmt.Println(l.WeekdayNarrow(time.Monday)) fmt.Println(l.WeekdayNarrow(time.Tuesday)) // ... var f64 float64 f64 = -10356.4523 // Number fmt.Println(l.FmtNumber(f64, 2)) // Currency fmt.Println(l.FmtCurrency(f64, 2, currency.CAD)) fmt.Println(l.FmtCurrency(f64, 2, currency.USD)) // Accounting fmt.Println(l.FmtAccounting(f64, 2, currency.CAD)) fmt.Println(l.FmtAccounting(f64, 2, currency.USD)) f64 = 78.12 // Percent fmt.Println(l.FmtPercent(f64, 0)) // Plural Rules for locale, so you know what rules you must cover fmt.Println(l.PluralsCardinal()) fmt.Println(l.PluralsOrdinal()) // Cardinal Plural Rules fmt.Println(l.CardinalPluralRule(1, 0)) fmt.Println(l.CardinalPluralRule(1.0, 0)) fmt.Println(l.CardinalPluralRule(1.0, 1)) fmt.Println(l.CardinalPluralRule(3, 0)) // Ordinal Plural Rules fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th // Range Plural Rules fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1 fmt.Println(l.RangePluralRule(1, 0, 2, 0)) // 1-2 fmt.Println(l.RangePluralRule(5, 0, 8, 0)) // 5-8 } ``` -------------------------------- ### Calling Afero Utilities Directly Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/spf13/afero/README.md Demonstrates how to call Afero utility functions directly by passing the filesystem as the first argument. This approach requires explicit instantiation of a filesystem. ```go fs := new(afero.MemMapFs) f, err := afero.TempFile(fs,"", "ioutil-test") ``` -------------------------------- ### Run Migrations within Go Application Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/golang-migrate/migrate/v4/database/postgres/TUTORIAL.md Example of how to initialize and run database migrations from within a Go application using the golang-migrate library. Ensure necessary database drivers and source drivers are imported. ```go import ( "log" "github.com/golang-migrate/migrate/v4" _ "github.com/golang-migrate/migrate/v4/database/postgres" _ "github.com/golang-migrate/migrate/v4/source/file" ) func main() { m, err := migrate.New( "file://db/migrations", "postgres://postgres:postgres@localhost:5432/example?sslmode=disable") if err != nil { log.Fatal(err) } if err := m.Up(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Testing with MemMapFs Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/spf13/afero/README.md Illustrates using Afero's MemMapFs for testing by creating a mock filesystem with specific files and directories. This ensures tests are isolated and reproducible. ```go func TestExist(t *testing.T) { appFS := afero.NewMemMapFs() // create test files and directories appFS.MkdirAll("src/a", 0755) afero.WriteFile(appFS, "src/a/b", []byte("file b"), 0644) afero.WriteFile(appFS, "src/c", []byte("file c"), 0644) name := "src/c" _, err := appFS.Stat(name) if os.IsNotExist(err) { t.Errorf("file \"%s\" does not exist.\n", name) } } ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/spf13/cobra/README.md Install the 'cobra-cli' command-line program to generate Cobra application scaffolding. ```go go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Implement RPC Client Codec Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/ugorji/go/codec/README.md Demonstrates how to establish an RPC client connection and create a client codec using the go-codec package. Supports both standard Go RPC and MsgpackSpec RPC clients. ```go //RPC Communication (client side) conn, err = net.Dial("tcp", "localhost:5555") rpcCodec := codec.GoRpc.ClientCodec(conn, h) //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h) client := rpc.NewClientWithCodec(rpcCodec) ``` -------------------------------- ### Example cURL Response Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gorilla/mux/README.md This is an example of the response received when making a request to the /foo endpoint, showing the CORS headers. ```bash * Trying ::1... * TCP_NODELAY set * Connected to localhost (::1) port 8080 (#0) > GET /foo HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.59.0 > Accept: */* > < HTTP/1.1 200 OK < Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS < Access-Control-Allow-Origin: * < Date: Fri, 28 Jun 2019 20:13:30 GMT < Content-Length: 3 < Content-Type: text/plain; charset=utf-8 < * Connection #0 to host localhost left intact foo ``` -------------------------------- ### Example cURL Request Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gorilla/mux/README.md This is an example of how to make a request to the /foo endpoint using cURL to test CORS headers. ```bash curl localhost:8080/foo -v ``` -------------------------------- ### Get JSON Data by Path Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/bytedance/sonic/README.md Search and retrieve JSON data using Get() with multiple paths. Use Index() for offset-based access, which is faster than scanning. ```go import "github.com/bytedance/sonic" input := []byte(`{"key1":[{},{"key2":{"key3":[1,2,3]}}]}`) // no path, returns entire json root, err := sonic.Get(input) raw := root.Raw() // == string(input) // multiple paths root, err := sonic.Get(input, "key1", 1, "key2") sub := root.Get("key3").Index(2).Int64() // == 3 ``` -------------------------------- ### serve - Start the Hasura Storage Server Source: https://context7.com/nhost/hasura-storage/llms.txt Starts the Hasura Storage HTTP server with various configuration options for S3, Hasura integration, and optional features like ClamAV. ```APIDOC ## serve ### Description Starts the Gin-based HTTP server, wires up S3 content storage, Hasura metadata storage, optional ClamAV integration, optional Fastly CDN middleware, and runs pending Postgres / Hasura migrations before accepting traffic. ### Method CLI Command ### Usage ```bash hasura-storage serve \ --public-url "http://localhost:8000" \ --api-root-prefix "/v1" \ --bind ":8000" \ --hasura-endpoint "http://localhost:8080/v1" \ --hasura-graphql-admin-secret "nhost-admin-secret" \ --s3-endpoint "http://localhost:9000" \ --s3-access-key "minioadmin" \ --s3-secret-key "minioadmin" \ --s3-region "us-east-1" \ --s3-bucket "default" \ --s3-root-folder "f215cf48-7458-4596-9aa5-2159fc6a3caf" \ --postgres-migrations \ --postgres-migrations-source "postgres://postgres:password@localhost:5432/postgres?sslmode=disable" \ --hasura-metadata \ --cors-allow-origins "*" \ --clamav-server "tcp://clamavd:3310" # optional antivirus ``` ### Equivalent YAML config (hasura-storage.yaml): ```yaml debug: true hasura-endpoint: http://localhost:8080/v1 hasura-metadata: true hasura-graphql-admin-secret: nhost-admin-secret s3-endpoint: "http://localhost:9000" s3-access-key: "minioadmin" s3-secret-key: "minioadmin" s3-disable-http: true s3-region: "us-east-1" s3-bucket: "default" s3-root-folder: "f215cf48-7458-4596-9aa5-2159fc6a3caf" postgres-migrations: true postgres-migrations-source: postgres://postgres:password@localhost:5432/postgres ``` ``` -------------------------------- ### Run Tests with pq Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/lib/pq/TESTS.md Execute tests for the pq library using the standard `go test` command. A running PostgreSQL server is required. Connection details can be overridden via environment variables. ```bash go test ``` -------------------------------- ### Combine Get and Unmarshal for Partial Schema Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/bytedance/sonic/README.md Use sonic.GetFromString to extract a specific node and then sonic.UnmarshalString to parse it into a partial schema. This is more performant than Get() + Node.Interface() when only a part of the JSON is needed. ```go import "github.com/bytedance/sonic" node, err := sonic.GetFromString(_TwitterJson, "statuses", 3, "user") var user User // your partial schema... err = sonic.UnmarshalString(node.Raw(), &user) ``` -------------------------------- ### Update Dependencies with go get and go mod tidy Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md After changing the import path, update your project dependencies using 'go get' and 'go mod tidy' commands. ```bash go get github.com/golang-jwt/jwt/v4 go mod tidy ``` -------------------------------- ### Generate and Open Docs Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/golang-migrate/migrate/v4/CONTRIBUTING.md Generate the project documentation using godoc and open it in your web browser. Repeatedly calling 'make docs' refreshes the server. ```bash make docs && make open-docs ``` -------------------------------- ### Route Precedence Example in Go Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gorilla/mux/README.md Routes are tested in the order they are added. The first matching route wins. Use PathPrefix("/") as a catch-all after specific routes. ```go r := mux.NewRouter() r.HandleFunc("/specific", specificHandler) r.PathPrefix("/").Handler(catchAllHandler) ``` -------------------------------- ### Canonical CORS Configuration Example Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/gin-contrib/cors/README.md Configure CORS with specific origins, methods, headers, and credentials. This example allows requests from 'https://foo.com' with PUT and PATCH methods, and custom origin validation for 'https://github.com'. ```go package main import ( "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() // CORS for https://foo.com and https://github.com origins, allowing: // - PUT and PATCH methods // - Origin header // - Credentials share // - Preflight requests cached for 12 hours router.Use(cors.New(cors.Config{ AllowOrigins: []string{"https://foo.com"}, AllowMethods: []string{"PUT", "PATCH"}, AllowHeaders: []string{"Origin"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, AllowOriginFunc: func(origin string) bool { return origin == "https://github.com" }, MaxAge: 12 * time.Hour, })) router.Run() } ``` -------------------------------- ### Get Service Version Source: https://context7.com/nhost/hasura-storage/llms.txt Returns the build version of the running hasura-storage instance. No authentication required. ```bash curl http://localhost:8000/v1/version # Response 200: # { "buildVersion": "0.6.1" } ``` -------------------------------- ### Basic fsnotify Watcher Usage in Go Source: https://github.com/nhost/hasura-storage/blob/main/vendor/github.com/fsnotify/fsnotify/README.md Demonstrates how to create a new watcher, listen for events and errors in a goroutine, add a directory to watch, and handle potential errors. It's recommended to close the watcher when done. ```go package main import ( "log" "github.com/fsnotify/fsnotify" ) func main() { // Create new watcher. watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() // Start listening for events. go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } log.Println("event:", event) if event.Has(fsnotify.Write) { log.Println("modified file:", event.Name) } case err, ok := <-watcher.Errors: if !ok { return } log.Println("error:", err) } } }() // Add a path. err = watcher.Add("/tmp") if err != nil { log.Fatal(err) } // Block main goroutine forever. <-make(chan struct{}) } ``` -------------------------------- ### Enter Nix Development Environment Source: https://github.com/nhost/hasura-storage/blob/main/DEVELOPMENT.md Use this command to enter the Nix development environment, ensuring consistency with CI. ```bash nix develop ```