### Install Apollo Adapter Source: https://github.com/gogf/gf/blob/master/contrib/config/apollo/README.MD Install the Apollo configuration adapter for GoFrame using go get. ```bash go get -u github.com/gogf/gf/contrib/config/apollo/v2 ``` -------------------------------- ### Install Kubecm Package Source: https://github.com/gogf/gf/blob/master/contrib/config/kubecm/README.MD Install the kubecm package using go get. ```bash go get -u github.com/gogf/gf/contrib/config/kubecm/v2 ``` -------------------------------- ### Install Polaris GoFrame Adapter Source: https://github.com/gogf/gf/blob/master/contrib/config/polaris/README.MD Install the Polaris configuration adapter for GoFrame using go get. ```bash go get -u github.com/gogf/gf/contrib/config/polaris/v2 ``` -------------------------------- ### Install Multiple Database Drivers Source: https://github.com/gogf/gf/blob/master/contrib/drivers/README.MD A list of `go get` commands to install various database drivers for gdb. Choose the one relevant to your project. ```shell go get github.com/gogf/gf/contrib/drivers/clickhouse/v2@latest go get github.com/gogf/gf/contrib/drivers/dm/v2@latest go get github.com/gogf/gf/contrib/drivers/gaussdb/v2@latest go get github.com/gogf/gf/contrib/drivers/mariadb/v2@latest go get github.com/gogf/gf/contrib/drivers/mssql/v2@latest go get github.com/gogf/gf/contrib/drivers/oceanbase/v2@latest go get github.com/gogf/gf/contrib/drivers/oracle/v2@latest go get github.com/gogf/gf/contrib/drivers/pgsql/v2@latest go get github.com/gogf/gf/contrib/drivers/sqlite/v2@latest go get github.com/gogf/gf/contrib/drivers/sqlitecgo/v2@latest go get github.com/gogf/gf/contrib/drivers/tidb/v2@latest ``` -------------------------------- ### File Registry Client Example Source: https://github.com/gogf/gf/blob/master/contrib/registry/file/README.MD Example of a client using the file registry. It initializes the registry and then makes multiple requests to a registered service. ```go package main import ( "fmt" "time" "github.com/gogf/gf/contrib/registry/file/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/gsvc" "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gfile" ) func main() { gsvc.SetRegistry(file.New(gfile.Temp("gsvc"))) client := g.Client() for i := 0; i < 100; i++ { res, err := client.Get(gctx.New(), `http://hello.svc/`) if err != nil { panic(err) } fmt.Println(res.ReadAllString()) res.Close() time.Sleep(time.Second) } } ``` -------------------------------- ### Install File Registry Source: https://github.com/gogf/gf/blob/master/contrib/registry/file/README.MD Install the file registry component using go get. It is recommended to use go.mod for dependency management. ```go go get -u -v github.com/gogf/gf/contrib/registry/file/v2 ``` ```go require github.com/gogf/gf/contrib/registry/file/v2 latest ``` -------------------------------- ### File Registry Server Example Source: https://github.com/gogf/gf/blob/master/contrib/registry/file/README.MD Example of a server using the file registry. It sets up the registry with a temporary directory and binds a handler for incoming requests. ```go package main import ( "github.com/gogf/gf/contrib/registry/file/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/net/gsvc" "github.com/gogf/gf/v2/os/gfile" ) func main() { gsvc.SetRegistry(file.New(gfile.Temp("gsvc"))) s := g.Server(`hello.svc`) s.BindHandler("/", func(r *ghttp.Request) { g.Log().Info(r.Context(), `request received`) r.Response.Write(`Hello world`) }) s.Run() } ``` -------------------------------- ### Install GoFrame Framework Source: https://github.com/gogf/gf/blob/master/README.MD Use this command to install the GoFrame framework. Ensure you are using Go version 2 or higher. ```bash go get -u github.com/gogf/gf/v2 ``` -------------------------------- ### Install Consul Adapter Source: https://github.com/gogf/gf/blob/master/contrib/config/consul/README.md Install the Consul configuration adapter for GoFrame using go get. ```go go get -u github.com/gogf/gf/contrib/config/consul/v2 ``` -------------------------------- ### Install otelmetric v2 Source: https://github.com/gogf/gf/blob/master/contrib/metric/otelmetric/README.MD Install the otelmetric module using go get. It is recommended to use go.mod for managing dependencies. ```go go get -u -v github.com/gogf/gf/contrib/metric/otelmetric/v2 ``` ```go require github.com/gogf/gf/contrib/metric/otelmetric/v2 latest ``` -------------------------------- ### Install MySQL Driver Source: https://github.com/gogf/gf/blob/master/contrib/drivers/README.MD Use `go get` to install the MySQL driver for gdb. This command fetches the latest version. ```shell go get github.com/gogf/gf/contrib/drivers/mysql/v2@latest ``` -------------------------------- ### Example: Sending a GET Request Source: https://github.com/gogf/gf/wiki/功能模块设计/HTTP客户端 Demonstrates how to send a GET request using the standalone ghttp.Get function and process the response. ```go package main import ( "fmt" "gitee.com/johng/gf/g/net/ghttp" ) func main() { if r, e := ghttp.Get("http://johng.cn"); e != nil { fmt.Println(e) } else { fmt.Println(string(r.ReadAll())) r.Close() } } ``` -------------------------------- ### Install ZooKeeper Registry Source: https://github.com/gogf/gf/blob/master/contrib/registry/zookeeper/README.MD Install the ZooKeeper registry component for GoFrame using go get or go.mod. ```bash go get -u -v github.com/gogf/gf/contrib/registry/zookeeper/v2 ``` ```go require github.com/gogf/gf/contrib/registry/zookeeper/v2 latest ``` -------------------------------- ### Install GoFrame Redis Adapter Source: https://github.com/gogf/gf/blob/master/contrib/nosql/redis/README.MD Install the Redis adapter for GoFrame using go get. This command fetches the necessary package for Redis integration. ```bash go get -u github.com/gogf/gf/contrib/nosql/redis/v2 ``` -------------------------------- ### Example YAML Configuration Source: https://github.com/gogf/gf/wiki/Web服务开发/配置管理 A sample configuration file demonstrating settings for template engine directory and MySQL database clusters. ```yaml # 模板引擎目录 viewpath: /home/www/templates/ # MySQL数据库配置 database: default: - host: 127.0.0.1 port: 3306 user: root pass: 123456 name: test type: mysql role: master charset: utf-8 priority: 1 - host: 127.0.0.1 port: 3306 user: root pass: 123456 name: test type: mysql role: master charset: utf-8 priority: 1 ``` -------------------------------- ### Etcd Registry Client Example Source: https://github.com/gogf/gf/blob/master/contrib/registry/etcd/README.MD Example of a GoFrame client using etcd for service discovery and making requests. It uses a round-robin load balancing strategy. ```go package main import ( "fmt" "time" "github.com/gogf/gf/contrib/registry/etcd/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/gsel" "github.com/gogf/gf/v2/net/gsvc" "github.com/gogf/gf/v2/os/gctx" ) func main() { gsvc.SetRegistry(etcd.New(`127.0.0.1:2379`)) gsel.SetBuilder(gsel.NewBuilderRoundRobin()) client := g.Client() for i := 0; i < 100; i++ { res, err := client.Get(gctx.New(), `http://hello.svc/`) if err != nil { panic(err) } fmt.Println(res.ReadAllString()) res.Close() time.Sleep(time.Second) } } ``` -------------------------------- ### Start Local Docker Services Source: https://github.com/gogf/gf/blob/master/CLAUDE.md Starts the default local stack of backing services required for certain tests. Use 'make docker cmd=start svc=' to start specific services. ```bash make docker ``` -------------------------------- ### Etcd Registry Server Example Source: https://github.com/gogf/gf/blob/master/contrib/registry/etcd/README.MD Example of a GoFrame server using etcd for service registration. Ensure etcd is running at 127.0.0.1:2379. ```go package main import ( "github.com/gogf/gf/contrib/registry/etcd/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/net/gsvc" ) func main() { gsvc.SetRegistry(etcd.New(`127.0.0.1:2379`)) s := g.Server(`hello.svc`) s.BindHandler("/", func(r *ghttp.Request) { g.Log().Info(r.Context(), `request received`) r.Response.Write(`Hello world`) }) s.Run() } ``` -------------------------------- ### Install Nacos Adapter Source: https://github.com/gogf/gf/blob/master/contrib/config/nacos/README.MD Install the Nacos configuration adapter for GoFrame v2 using go get. ```bash go get -u github.com/gogf/gf/contrib/config/nacos/v2 ``` -------------------------------- ### Import Boot Package in Main Application Source: https://github.com/gogf/gf/blob/master/contrib/config/apollo/README.MD Import the custom boot package in your main.go to ensure the Apollo configuration is loaded. This example demonstrates checking configuration availability, retrieving all data, and getting a specific value. ```go package main import ( _ "github.com/gogf/gf/example/config/apollo/boot" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func main() { var ctx = gctx.GetInitCtx() // Available checks. g.Dump(g.Cfg().Available(ctx)) // All key-value configurations. g.Dump(g.Cfg().Data(ctx)) // Retrieve certain value by key. g.Dump(g.Cfg().MustGet(ctx, "server.address")) } ``` -------------------------------- ### Install gf CLI (Go Modules) Source: https://github.com/gogf/gf/blob/master/cmd/gf/README.MD Installs the gf CLI tool using Go modules. You can install the latest version or a specific version. ```shell go install github.com/gogf/gf/cmd/gf/v2@latest # latest version ``` ```shell go install github.com/gogf/gf/cmd/gf/v2@v2.5.5 # certain version(should be >= v2.5.5) ``` -------------------------------- ### Install gf CLI (Mac/Linux) Source: https://github.com/gogf/gf/blob/master/cmd/gf/README.MD Installs the gf CLI tool using a pre-compiled binary from GitHub releases. It downloads the binary, makes it executable, installs it, and then removes the downloaded file. Note: If using zsh, you might need to alias gf to resolve conflicts with git fetch. ```shell wget -O gf https://github.com/gogf/gf/releases/latest/download/gf_$(go env GOOS)_$(go env GOARCH) && chmod +x gf && ./gf install -y && rm ./gf ``` -------------------------------- ### Install GoFrame Polaris Registry Source: https://github.com/gogf/gf/blob/master/contrib/registry/polaris/README.MD Install the Polaris registry component for GoFrame using go get. ```bash go get -u -v github.com/gogf/gf/contrib/registry/polaris/v2 ``` -------------------------------- ### Import Boot Package in Main Application Source: https://github.com/gogf/gf/blob/master/contrib/config/polaris/README.MD Import the custom boot package at the top of your main.go to ensure the Polaris configuration adapter is active. This example demonstrates how to access configuration values after setup. ```go package main import ( _ "github.com/gogf/gf/example/config/polaris/boot" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func main() { var ctx = gctx.GetInitCtx() // Available checks. g.Dump(g.Cfg().Available(ctx)) // All key-value configurations. g.Dump(g.Cfg().Data(ctx)) // Retrieve certain value by key. g.Dump(g.Cfg().MustGet(ctx, "server.address")) } ``` -------------------------------- ### Simple Echo TCPServer Example Source: https://github.com/gogf/gf/wiki/网络服务开发/TCPServer Demonstrates how to create and run a basic TCP echo server. It listens on a specified address and echoes back any received data to the client. ```go package main import ( "net" "gitee.com/johng/gf/g/net/gtcp" ) func main() { gtcp.NewServer(":8999", func(conn net.Conn) { for { buffer := make([]byte, 1024) if length, err := conn.Read(buffer); err == nil { conn.Write(append([]byte("> "), buffer[0 : length]...)) } } }).Run() ``` -------------------------------- ### Import Boot Package in Main Application Source: https://github.com/gogf/gf/blob/master/contrib/config/consul/README.md Import the custom boot package at the top of your main.go file to ensure the Consul configuration adapter is initialized before application logic runs. This example demonstrates how to access configuration values after setup. ```go package main import ( _ "github.com/gogf/gf/example/config/consul/boot" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func main() { var ctx = gctx.GetInitCtx() // Available checks. g.Dump(g.Cfg().Available(ctx)) // All key-value configurations. g.Dump(g.Cfg().Data(ctx)) // Retrieve certain value by key. g.Dump(g.Cfg().MustGet(ctx, "redis.addr")) } ``` -------------------------------- ### Polaris Service Server Example Source: https://github.com/gogf/gf/blob/master/contrib/registry/polaris/README.MD Example of a GoFrame server using Polaris for service registration. Ensure Polaris server is running and accessible. ```go package main import ( "github.com/polarismesh/polaris-go/pkg/config" "github.com/gogf/gf/contrib/registry/polaris/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/net/gsvc" ) func main() { conf := config.NewDefaultConfiguration([]string{"183.47.111.80:8091"}) // TTL egt 2*time.Second gsvc.SetRegistry(polaris.NewWithConfig(conf, polaris.WithTTL(10))) s := g.Server(`hello.svc`) s.BindHandler("/", func(r *ghttp.Request) { g.Log().Info(r.Context(), `request received`) r.Response.Write(`Hello world`) }) s.Run() } ``` -------------------------------- ### Example Kubernetes ConfigMap Source: https://github.com/gogf/gf/blob/master/contrib/config/kubecm/README.MD An example of a Kubernetes ConfigMap resource containing configuration data. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: test-configmap data: config.yaml: | # HTTP service. server: address: ":8888" openapiPath: "/api.json" swaggerPath: "/swagger" accessLogEnabled: true ``` -------------------------------- ### Registering "Hello World" with Domain Binding Source: https://github.com/gogf/gf/wiki/Web服务开发/服务注册 Example of registering a callback function to a specific domain ('localhost') using the Domain method. Accessing this service via other domains (e.g., 127.0.0.1) will result in a 404 error. ```go package main import "gitee.com/johng/gf/g/net/ghttp" func init() { ghttp.GetServer().Domain("localhost").BindHandler("/", func(r *ghttp.Request) { r.Response.WriteString("Hello World!") }) } ``` -------------------------------- ### Main Application with MySQL Driver Source: https://github.com/gogf/gf/blob/master/contrib/drivers/README.MD Example of importing the MySQL driver in `main.go` alongside other necessary packages. The driver is typically imported at the top of the file. ```go package main import ( _ "github.com/gogf/gf/contrib/drivers/mysql/v2" // Other imported packages. ) func main() { // Main logics. } ``` -------------------------------- ### Polaris Service Client Example Source: https://github.com/gogf/gf/blob/master/contrib/registry/polaris/README.MD Example of a GoFrame client using Polaris for service discovery. This client will repeatedly call the 'hello.svc' service. ```go package main import ( "fmt" "time" "github.com/polarismesh/polaris-go/pkg/config" "github.com/gogf/gf/contrib/registry/polaris/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/gsvc" "github.com/gogf/gf/v2/os/gctx" ) func main() { conf := config.NewDefaultConfiguration([]string{"183.47.111.80:8091"}) gsvc.SetRegistry(polaris.NewWithConfig(conf, polaris.WithTTL(10))) for i := 0; i < 100; i++ { res, err := g.Client().Get(gctx.New(), `http://hello.svc/`) if err != nil { panic(err) } fmt.Println(res.ReadAllString()) res.Close() time.Sleep(time.Second) } } ``` -------------------------------- ### Install GoFrame Consul Registry Source: https://github.com/gogf/gf/blob/master/contrib/registry/consul/README.MD Install the GoFrame Consul registry component using go get or by adding it to your go.mod file. ```bash go get -u github.com/gogf/gf/contrib/registry/consul/v2 ``` ```bash require github.com/gogf/gf/contrib/registry/consul/v2 latest ``` -------------------------------- ### Nacos Server Example Source: https://github.com/gogf/gf/blob/master/contrib/registry/nacos/README.MD Example of a GoFrame server using Nacos for service registration. It sets up the Nacos registry and binds a handler for the root path. ```go package main import ( "github.com/gogf/gf/contrib/registry/nacos/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/net/gsvc" ) func main() { gsvc.SetRegistry(nacos.New(`127.0.0.1:8848`). SetClusterName("DEFAULT"). SetGroupName("DEFAULT_GROUP")) s := g.Server(`hello.svc`) s.BindHandler("/", func(r *ghttp.Request) { g.Log().Info(r.Context(), `request received`) r.Response.Write(`Hello world`) }) s.Run() } ``` -------------------------------- ### Nacos Client Example Source: https://github.com/gogf/gf/blob/master/contrib/registry/nacos/README.MD Example of a GoFrame client using Nacos for service discovery. It sets up the Nacos registry, a round-robin load balancer, and makes multiple requests to a registered service. ```go package main import ( "fmt" "time" "github.com/gogf/gf/contrib/registry/nacos/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/gsel" "github.com/gogf/gf/v2/net/gsvc" "github.com/gogf/gf/v2/os/gctx" ) func main() { gsvc.SetRegistry(nacos.New(`127.0.0.1:8848`)) gsel.SetBuilder(gsel.NewBuilderRoundRobin()) client := g.Client() for i := 0; i < 100; i++ { res, err := client.Get(gctx.New(), `http://hello.svc/`) if err != nil { panic(err) } fmt.Println(res.ReadAllString()) res.Close() time.Sleep(time.Second) } } ``` -------------------------------- ### Get Command-Line Options by Key Source: https://github.com/gogf/gf/wiki/功能模块设计/命令行模块 Retrieve command-line options by their key name. Supports formats like '--key=value' or '-key=value'. ```go gcmd.Option.Get("timeout") ``` ```go gcmd.Option.Get("logpath") ``` -------------------------------- ### Send GET Request and Print Response Source: https://github.com/gogf/gf/wiki/功能模块设计/HTTP客户端 Demonstrates how to send a GET request using the ghttp.Get function and process the response. Remember to close the response object after reading its content. ```go if r, e := ghttp.Get("http://johng.cn"); e != nil { fmt.Println(e) } else { fmt.Println(string(r.ReadAll())) r.Close() } ``` -------------------------------- ### Install etcd Registry Source: https://github.com/gogf/gf/blob/master/contrib/registry/etcd/README.MD Install the etcd registry component for GoFrame. It is recommended to use go.mod for managing dependencies. ```go go get -u -v github.com/gogf/gf/contrib/registry/etcd/v2 ``` ```go require github.com/gogf/gf/contrib/registry/etcd/v2 latest ``` -------------------------------- ### Session Increment Example in Go Source: https://github.com/gogf/gf/wiki/Web服务开发/Session Demonstrates how to increment a session variable. Access the session via `r.Session` and use `GetInt` and `Set` to manage the counter. This example is suitable for tracking user visits or simple state. ```go package demo import ( "strconv" "gitee.com/johng/gf/g/net/ghttp" ) func init() { ghttp.GetServer().BindHandler("/session", Session) } func Session(r *ghttp.Request) { id := r.Session.GetInt("id") r.Session.Set("id", id + 1) r.Response.WriteString("id:" + strconv.Itoa(id)) } ``` -------------------------------- ### Import MariaDB Driver Source: https://github.com/gogf/gf/blob/master/contrib/drivers/README.MD Import the MariaDB driver for use with gdb. Ensure the driver is installed before importing. ```go import _ "github.com/gogf/gf/contrib/drivers/mariadb/v2" ``` -------------------------------- ### Example: File Upload Source: https://github.com/gogf/gf/wiki/功能模块设计/HTTP客户端 Illustrates how to perform a file upload using a POST request. The file is specified using the '@file:' prefix followed by the file path. ```go package main import ( "fmt" "gitee.com/johng/gf/g/net/ghttp" "gitee.com/johng/gf/g/os/glog" ) func main() { path := "/home/john/Workspace/Go/gitee.com/johng/gf/version.go" r, e := ghttp.Post("http://127.0.0.1:8199/upload", "name=john&age=18&upload-file=@file:" + path) if e != nil { glog.Error(e) } else { fmt.Println(string(r.ReadAll())) r.Close() } } ``` -------------------------------- ### Modify Configuration Directory via Command Line Source: https://github.com/gogf/gf/wiki/Web服务开发/配置管理 Example of how to specify a custom configuration directory using a command-line argument. ```shell ./main --cfgpath=/opt/config/ ``` -------------------------------- ### Basic otelmetric Example Source: https://github.com/gogf/gf/blob/master/contrib/metric/otelmetric/README.MD Demonstrates the usage of various metric types (Counter, UpDownCounter, Histogram, Observable metrics) with OpenTelemetry exporter and Prometheus HTTP handler. ```go package main import ( "context" "github.com/prometheus/client_golang/prometheus/promhttp" "go.opentelemetry.io/otel/exporters/prometheus" "go.opentelemetry.io/otel/sdk/metric" "github.com/gogf/gf/contrib/metric/otelmetric/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gmetric" ) var ( meter = gmetric.GetGlobalProvider().Meter(gmetric.MeterOption{ Instrument: "github.com/gogf/gf/example/metric/basic", InstrumentVersion: "v1.0", }) counter = meter.MustCounter( "goframe.metric.demo.counter", gmetric.MetricOption{ Help: "This is a simple demo for Counter usage", Unit: "bytes", Attributes: gmetric.Attributes{ gmetric.NewAttribute("const_label_1", 1), }, }, ) upDownCounter = meter.MustUpDownCounter( "goframe.metric.demo.updown_counter", gmetric.MetricOption{ Help: "This is a simple demo for UpDownCounter usage", Unit: "%", Attributes: gmetric.Attributes{ gmetric.NewAttribute("const_label_2", 2), }, }, ) histogram = meter.MustHistogram( "goframe.metric.demo.histogram", gmetric.MetricOption{ Help: "This is a simple demo for histogram usage", Unit: "ms", Attributes: gmetric.Attributes{ gmetric.NewAttribute("const_label_3", 3), }, Buckets: []float64{0, 10, 20, 50, 100, 500, 1000, 2000, 5000, 10000}, }, ) observableCounter = meter.MustObservableCounter( "goframe.metric.demo.observable_counter", gmetric.MetricOption{ Help: "This is a simple demo for ObservableCounter usage", Unit: "%", Attributes: gmetric.Attributes{ gmetric.NewAttribute("const_label_4", 4), }, }, ) observableUpDownCounter = meter.MustObservableUpDownCounter( "goframe.metric.demo.observable_updown_counter", gmetric.MetricOption{ Help: "This is a simple demo for ObservableUpDownCounter usage", Unit: "%", Attributes: gmetric.Attributes{ gmetric.NewAttribute("const_label_5", 5), }, }, ) observableGauge = meter.MustObservableGauge( "goframe.metric.demo.observable_gauge", gmetric.MetricOption{ Help: "This is a simple demo for ObservableGauge usage", Unit: "%", Attributes: gmetric.Attributes{ gmetric.NewAttribute("const_label_6", 6), }, }, ) ) func main() { var ctx = gctx.New() // Callback for observable metrics. meter.MustRegisterCallback(func(ctx context.Context, obs gmetric.Observer) error { obs.Observe(observableCounter, 10) obs.Observe(observableUpDownCounter, 20) obs.Observe(observableGauge, 30) return nil }, observableCounter, observableUpDownCounter, observableGauge) // Prometheus exporter to export metrics as Prometheus format. exporter, err := prometheus.New( prometheus.WithoutCounterSuffixes(), prometheus.WithoutUnits(), ) if err != nil { g.Log().Fatal(ctx, err) } // OpenTelemetry provider. provider := otelmetric.MustProvider(metric.WithReader(exporter)) provider.SetAsGlobal() defer provider.Shutdown(ctx) // Counter. counter.Inc(ctx) counter.Add(ctx, 10) // UpDownCounter. upDownCounter.Inc(ctx) upDownCounter.Add(ctx, 10) upDownCounter.Dec(ctx) // Record values for histogram. histogram.Record(1) histogram.Record(20) histogram.Record(30) histogram.Record(101) histogram.Record(2000) histogram.Record(9000) histogram.Record(20000) // HTTP Server for metrics exporting. s := g.Server() s.BindHandler("/metrics", ghttp.WrapH(promhttp.Handler())) s.SetPort(8000) s.Run() } ``` -------------------------------- ### File Header Comment Example Source: https://github.com/gogf/gf/blob/master/AGENTS.md A file-purpose comment should be placed immediately before the package declaration in a Go source file. ```go // Package plugin implements plugin manifest discovery, lifecycle orchestration, // governance metadata synchronization, and host integration for LinaPro plugins. package plugin ``` -------------------------------- ### TCPServer Method Signatures Source: https://github.com/gogf/gf/wiki/网络服务开发/TCPServer Lists the available methods for the TCPServer. These include functions to get or create a server instance, and methods to configure and run the server. ```go func GetServer(names ...string) *Server func NewServer(address string, handler func(net.Conn), names ...string) *Server func (s *Server) Run() error func (s *Server) SetAddress(address string) func (s *Server) SetHandler(handler func(net.Conn)) ``` -------------------------------- ### Modify Configuration Directory via Environment Variable Source: https://github.com/gogf/gf/wiki/Web服务开发/配置管理 Example of how to specify a custom configuration directory using an environment variable. ```shell cfgpath=/opt/config/; ./main ``` -------------------------------- ### Example: Sending a POST Request Source: https://github.com/gogf/gf/wiki/功能模块设计/HTTP客户端 Illustrates sending a POST request with form data using the standalone ghttp.Post function and handling the response. ```go package main import ( "fmt" "gitee.com/johng/gf/g/net/ghttp" ) func main() { if r, e := ghttp.Post("http://127.0.0.1:8199/form", "name=john&age=18"); e != nil { fmt.Println(e) } else { fmt.Println(string(r.ReadAll())) r.Close() } } ``` -------------------------------- ### Setting a Routing Rule for Pseudo-Static Links Source: https://github.com/gogf/gf/wiki/Web服务开发/路由控制 Demonstrates how to convert a pseudo-static URL pattern to a standard GET parameter URL using SetRule. This is useful for making URLs more user-friendly and SEO-compatible. Ensure the regular expression correctly captures and replaces URL segments. ```go package demo import "gitee.com/johng/gf/g/net/ghttp" func init() { ghttp.GetServer().BindHandler("/list", List) ghttp.GetServer().Router.SetRule(`\/list\/page\/(\d+)[\/\?]*`, "/list?page=$1&") } func List(r *ghttp.Request) { r.Response.WriteString("list page:" + r.GetQueryString("page")) } ``` -------------------------------- ### Manage Dockerized Services Source: https://github.com/gogf/gf/blob/master/AGENTS.md Commands to manage the local Docker stack for testing backing services like MySQL. Use 'make docker' to start the default stack or specify services. ```bash make docker ``` ```bash make docker cmd=start svc=mysql ``` ```bash make docker cmd=stop svc=mysql ``` -------------------------------- ### File Upload Handler Example Source: https://github.com/gogf/gf/wiki/Web服务开发/输入输出 Demonstrates how to handle file uploads in a web server using the ghttp.Request. It saves the uploaded file to the server's temporary directory and ensures the file pointer is closed. ```go package demo import ( "gitee.com/johng/gf/g/os/gfile" "gitee.com/johng/gf/g/net/ghttp" ) func Upload(r *ghttp.Request) { if f, h, e := r.FormFile("upload-file"); e == nil { defer f.Close() fname := gfile.Basename(h.Filename) buffer := make([]byte, h.Size) f.Read(buffer) gfile.PutBinContents("/tmp/" + fname, buffer) r.Response.WriteString(fname + " uploaded successly") } else { r.Response.WriteString(e.Error()) } } func UploadShow(r *ghttp.Request) { r.Response.WriteString(` 上传文件
`) } func init() { ghttp.GetServer().BindHandler("/upload", Upload) ghttp.GetServer().BindHandler("/upload/show", UploadShow) } ``` -------------------------------- ### Web Server Initialization and Service Registration Source: https://github.com/gogf/gf/wiki/Web服务开发/服务注册 Illustrates how to initialize the ghttp server and run it, with service registrations typically handled in the package's init() function. It shows importing a package that contains its own service registrations. ```go package main import ( "gitee.com/johng/gf/g/net/ghttp" _ "gitee.com/johng/gf/geg/frame/mvc/controller/demo" ) func main() { ghttp.GetServer().SetPort(8199) ghttp.GetServer().Run() } ``` -------------------------------- ### Registering a Callback Function for "Hello World" Source: https://github.com/gogf/gf/wiki/Web服务开发/服务注册 Demonstrates the simplest service registration using BindHandler to associate a URI with a callback function. The callback receives a ghttp.Request object for handling request parameters and returning responses. ```go package main import "gitee.com/johng/gf/g/net/ghttp" func init() { ghttp.GetServer().BindHandler("/", func(r *ghttp.Request) { r.Response.WriteString("Hello World!") }) } ``` -------------------------------- ### Setting a Routing Rule for Content Patching Source: https://github.com/gogf/gf/wiki/Web服务开发/路由控制 Demonstrates how to use SetPatchRule to automatically convert specific URL patterns within response content to a different format, typically for pseudo-static links. This simplifies output formatting by handling replacements globally. The example converts a dynamic link to a pseudo-static one. ```go package demo import "gitee.com/johng/gf/g/net/ghttp" func init() { ghttp.GetServer().BindHandler("/router-patch", RouterPatch) ghttp.GetServer().Router.SetPatchRule(`\/list\?page=(\d+)&*`, "/list/page/$1?") } func RouterPatch(r *ghttp.Request) { r.Response.WriteString(`page2`) } ``` -------------------------------- ### Importing Package for Automatic Service Registration Source: https://github.com/gogf/gf/wiki/Web服务开发/服务注册 Demonstrates using a blank import to include a package that contains its own service registration logic within its init() function. This allows for modular registration of controllers, objects, and handlers. ```go import _ "gitee.com/johng/gf/geg/frame/mvc/controller/demo" ``` -------------------------------- ### Install GoFrame Nacos Registry Source: https://github.com/gogf/gf/blob/master/contrib/registry/nacos/README.MD Install the nacos registry component for GoFrame. It is recommended to use go.mod for managing dependencies. ```go go get -u -v github.com/gogf/gf/contrib/registry/nacos/v2 ``` ```go require github.com/gogf/gf/contrib/ અ/registry/nacos/v2 latest ``` -------------------------------- ### Create Custom Boot Package for Apollo Source: https://github.com/gogf/gf/blob/master/contrib/config/apollo/README.MD Create a custom boot package to initialize the Apollo adapter for global configuration. This should be imported early in your application. ```go package boot import ( "github.com/gogf/gf/contrib/config/apollo/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func init() { var ( ctx = gctx.GetInitCtx() appId = "SampleApp" cluster = "default" ip = "http://localhost:8080" ) // Create apollo Client that implements gcfg.Adapter. adapter, err := apollo.New(ctx, apollo.Config{ AppID: appId, IP: ip, Cluster: cluster, }) if err != nil { g.Log().Fatalf(ctx, `%+v`, err) } // Change the adapter of default configuration instance. g.Cfg().SetAdapter(adapter) } ``` -------------------------------- ### Generate and Use RSA Key Pair with PKCS#1 v1.5 Padding Source: https://github.com/gogf/gf/blob/master/crypto/grsa/README.md Illustrates generating a default RSA key pair and performing encryption and decryption using the legacy PKCS#1 v1.5 padding scheme. Use this only for backward compatibility. ```go package main import ( "fmt" "github.com/gogf/gf/v2/crypto/grsa" ) func main() { // Generate a default RSA key pair (2048 bits) privateKey, publicKey, err := grsa.GenerateDefaultKeyPair() if err != nil { panic(err) } // Data to encrypt plainText := []byte("Hello, World!") // Encrypt with public key (PKCS#1 v1.5 - legacy) cipherText, err := grsa.Encrypt(plainText, publicKey) if err != nil { panic(err) } // Decrypt with private key decryptedText, err := grsa.Decrypt(cipherText, privateKey) if err != nil { panic(err) } fmt.Println(string(decryptedText)) // Output: Hello, World! } ``` -------------------------------- ### Using Default Goroutine Pool with Size Limit Source: https://github.com/gogf/gf/wiki/功能模块设计/Goroutine池 Demonstrates how to set the size of the default goroutine pool and add tasks. It also shows how to monitor the pool's size and pending jobs using gtime.SetInterval. ```go package main import ( "time" "fmt" "gitee.com/johng/gf/g/os/gtime" "gitee.com/johng/gf/g/os/grpool" ) func job() { time.Sleep(1*time.Second) } func main() { grpool.SetSize(10) for i := 0; i < 1000; i++ { grpool.Add(job) } gtime.SetInterval(2*time.Second, func() bool { fmt.Println("size:", grpool.Size()) fmt.Println("jobs:", grpool.Jobs()) return true }) select {} } ``` -------------------------------- ### Basic Syntax and Variable Access Source: https://github.com/gogf/gf/wiki/Web服务开发/模板引擎 Demonstrates basic template syntax using {{}} for tags, '.' for object values, and '$' for context variables. Supports standard strings, raw strings, and bytes. ```GoTemplate {{"string"}} {{`raw string`}} {{'c'}} {{print nil}} ``` -------------------------------- ### Import Boot Package in Main Application Source: https://github.com/gogf/gf/blob/master/contrib/config/kubecm/README.MD Import the custom boot package at the top of your main.go file to ensure configurations are loaded before other packages. ```go package main import ( _ "github.com/gogf/gf/example/config/kubecm/boot_in_pod" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func main() { var ctx = gctx.GetInitCtx() // Available checks. g.Dump(g.Cfg().Available(ctx)) // All key-value configurations. g.Dump(g.Cfg().Data(ctx)) // Retrieve certain value by key. g.Dump(g.Cfg().MustGet(ctx, "server.address")) } ``` -------------------------------- ### GF genv Module: Environment Variable Functions Source: https://github.com/gogf/gf/wiki/功能模块设计/环境变量模块 Provides common functions for interacting with environment variables. Use `Get` to retrieve a variable, `Set` to set one, `Remove` to delete one, and `All` to get all variables. ```go func All() []string func Get(k string) string func Remove(k string) error func Set(k, v string) error ``` -------------------------------- ### Date and Time Retrieval Source: https://github.com/gogf/gf/wiki/功能模块设计/时间模块 Functions to get the current date and time in different formats. ```APIDOC ## Date() ### Description Retrieves the current date as a string. ### Method ```go func Date() string ``` ## Datetime() ### Description Retrieves the current date and time as a string. ### Method ```go func Datetime() string ``` ``` -------------------------------- ### Example: Sending a DELETE Request Source: https://github.com/gogf/gf/wiki/功能模块设计/HTTP客户端 Demonstrates sending a DELETE request using the standalone ghttp.Delete function. ```go package main import ( "fmt" "gitee.com/johng/gf/g/net/ghttp" ) func main() { if r, e := ghttp.Delete("http://127.0.0.1:8199/user", "10000"); e != nil { fmt.Println(e) } else { fmt.Println(string(r.ReadAll())) r.Close() } } ``` -------------------------------- ### Get Array by Pattern Source: https://github.com/gogf/gf/wiki/功能模块设计/数据编码解析 Retrieves a value as a slice of interfaces from the Parser using a hierarchical pattern string. ```go func (p *Parser) GetArray(pattern string) []interface{} ``` -------------------------------- ### Get Map by Pattern Source: https://github.com/gogf/gf/wiki/功能模块设计/数据编码解析 Retrieves a map[string]interface{} value from the Parser using a hierarchical pattern string. ```go func (p *Parser) GetMap(pattern string) map[string]interface{} ``` -------------------------------- ### Get Command-Line Arguments by Index Source: https://github.com/gogf/gf/wiki/功能模块设计/命令行模块 Retrieve command-line arguments using their zero-based index. Useful for positional arguments. ```go gcmd.Value.Get(0) ``` ```go gcmd.Value.Get(1) ``` -------------------------------- ### Build and Test Root Module Source: https://github.com/gogf/gf/blob/master/AGENTS.md Build all packages in the root module and run tests with race detection enabled. Use these commands from the root of the repository. ```bash go build ./... ``` ```bash go test ./... -count=1 -race ``` -------------------------------- ### Create Custom Boot Package for Polaris Config Source: https://github.com/gogf/gf/blob/master/contrib/config/polaris/README.MD Set up a custom boot package to initialize the Polaris configuration adapter globally. This ensures configuration is loaded from Polaris before other packages initialize. ```go package boot import ( "github.com/gogf/gf/contrib/config/polaris/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func init() { var ( ctx = gctx.GetInitCtx() namespace = "default" fileGroup = "goframe" fileName = "config.yaml" path = "testdata/polaris.yaml" logDir = "/tmp/polaris/log" ) // Create polaris Client that implements gcfg.Adapter. adapter, err := polaris.New(ctx, polaris.Config{ Namespace: namespace, FileGroup: fileGroup, FileName: fileName, Path: path, LogDir: logDir, Watch: true, }) if err != nil { g.Log().Fatalf(ctx, `%+v`, err) } // Change the adapter of default configuration instance. g.Cfg().SetAdapter(adapter) } ``` -------------------------------- ### Import PostgreSQL Driver Source: https://github.com/gogf/gf/blob/master/contrib/drivers/README.MD Import the PostgreSQL driver to enable gdb to connect to PostgreSQL databases. ```go import _ "github.com/gogf/gf/contrib/drivers/pgsql/v2" ``` -------------------------------- ### Get Value by Pattern Source: https://github.com/gogf/gf/wiki/功能模块设计/数据编码解析 Retrieves a value from the Parser using a hierarchical pattern string. The pattern uses '.' to separate levels. ```go func (p *Parser) Get(pattern string) interface{} ``` -------------------------------- ### Manage Specific Docker Service Source: https://github.com/gogf/gf/blob/master/CLAUDE.md Starts or stops a specific backing service (e.g., mysql) within the local Docker stack. ```bash make docker cmd=start svc=mysql ``` ```bash make docker cmd=stop svc=mysql ``` -------------------------------- ### HTTP Server with Consul Registry Source: https://github.com/gogf/gf/blob/master/contrib/registry/consul/README.MD Example of an HTTP server registering itself with Consul. Ensure Consul is running and accessible at the specified address. ```go package main import ( "context" "github.com/gogf/gf/contrib/registry/consul/v2" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/net/gsvc" ) func main() { registry, err := consul.New(consul.WithAddress("127.0.0.1:8500")) if err != nil { g.Log().Fatal(context.Background(), err) } gsvc.SetRegistry(registry) s := g.Server("hello.svc") s.BindHandler("/", func(r *ghttp.Request) { g.Log().Info(r.Context(), "request received") r.Response.Write("Hello world") }) s.Run() } ``` -------------------------------- ### gf CLI Help Source: https://github.com/gogf/gf/blob/master/cmd/gf/README.MD Displays the help information for the gf CLI tool, outlining available commands and options. ```shell $ gf -h USAGE gf COMMAND [OPTION] COMMAND up upgrade GoFrame version/tool to latest one in current project env show current Golang environment variables fix auto fixing codes after upgrading to new GoFrame version run running go codes with hot-compiled-like feature gen automatically generate go files for dao/do/entity/pb/pbentity tpl template parsing and building commands init create and initialize an empty GoFrame project pack packing any file/directory to a resource file, or a go file build cross-building go project for lots of platforms docker build docker image for current GoFrame project install install gf binary to system (might need root/admin permission) version show version information of current binary doc download https://pages.goframe.org/ to run locally OPTION -y, --yes all yes for all command without prompt ask -v, --version show version information of current binary -d, --debug show internal detailed debugging information -h, --help more information about this command ADDITIONAL Use "gf COMMAND -h" for details about a command. ``` -------------------------------- ### Using Parentheses for Function Arguments Source: https://github.com/gogf/gf/wiki/Web服务开发/模板引擎 Shows how to nest function calls, using the output of one function as an argument to another, similar to `fmt.Sprintf`. ```go {{printf "nums is %s %d" (printf "%d %d" 1 2) 3}} ``` -------------------------------- ### Get Integer by Pattern Source: https://github.com/gogf/gf/wiki/功能模块设计/数据编码解析 Retrieves an integer value from the Parser using a hierarchical pattern string. Returns 0 if the value is not an integer or cannot be converted. ```go func (p *Parser) GetInt(pattern string) int ``` -------------------------------- ### Read Database Host Configuration Source: https://github.com/gogf/gf/wiki/Web服务开发/配置管理 Demonstrates reading a specific configuration value (database host) from the global configuration using hierarchical access. ```go package demo import ( "gitee.com/johng/gf/g/net/ghttp" "gitee.com/johng/gf/g/frame/gins" ) func init() { ghttp.GetServer().BindHandler("/config", func (r *ghttp.Request) { r.Response.WriteString(gins.Config().GetString("database.default.0.host")) }) } ``` -------------------------------- ### Get Float64 by Pattern Source: https://github.com/gogf/gf/wiki/功能模块设计/数据编码解析 Retrieves a float64 value from the Parser using a hierarchical pattern string. Returns 0.0 if the value is not a float64 or cannot be converted. ```go func (p *Parser) GetFloat64(pattern string) float64 ``` -------------------------------- ### Get Float32 by Pattern Source: https://github.com/gogf/gf/wiki/功能模块设计/数据编码解析 Retrieves a float32 value from the Parser using a hierarchical pattern string. Returns 0.0 if the value is not a float32 or cannot be converted. ```go func (p *Parser) GetFloat32(pattern string) float32 ```