## 1. Project Overview & Quickstart (gin-gonic/examples) ## File: README.md # Gin Examples [](https://github.com/gin-gonic/examples/actions/workflows/trivy-scan.yml) [](https://github.com/gin-gonic/examples/actions/workflows/golangci-lint.yml) This repository contains a number of ready-to-run examples demonstrating various use cases of [Gin](https://github.com/gin-gonic/gin). Refer to the [Gin documentation](https://gin-gonic.com/en/docs/) for how to execute the example tutorials. ## Contributing Are you missing an example? Please feel free to open an issue or commit one pull request. Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for instructions on how to contribute. --- ## File: app-engine/gophers/README.md # Guide to run Gin under App Engine LOCAL Development Server 1. Download, install and setup Go in your computer. (That includes setting your `$GOPATH`.) 2. Download SDK for your platform from [here](https://cloud.google.com/appengine/docs/standard/go/download): `https://cloud.google.com/appengine/docs/standard/go/download` 3. Download Gin source code using: `$ go get github.com/gin-gonic/examples` 4. Navigate to examples folder: `$ cd $GOPATH/src/github.com/gin-gonic/examples/app-engine/` 5. Run it: `$ dev_appserver.py .` (notice that you have to run this script by Python2) --- ## File: assets-in-binary/README.md # Assets in Binary This project demonstrates how to embed static files and file trees into a Go executable using the `//go:embed` directive introduced in Go 1.16. The embedded files can be accessed at runtime, allowing for easy distribution of assets within a single binary. ## Project Structure - **assets/**: Contains static assets such as images and icons. - `favicon.ico`: The favicon for the website. - `images/`: Directory containing example images. - **templates/**: Contains HTML templates used by the application. - `index.tmpl`: The main template for the homepage. - `foo/bar.tmpl`: The template for the "Foo" page. - **go.mod**: The Go module file, listing the dependencies required for the project. - **go.sum**: The Go checksum file, ensuring the integrity of the dependencies. - **main.go**: The main application file, setting up the web server and routes. ## Dependencies The project uses the following dependencies: - `github.com/gin-gonic/gin`: A web framework for Go. - `github.com/bytedance/sonic`: A high-performance JSON library. - `github.com/gabriel-vasile/mimetype`: A library for detecting MIME types. - And various other indirect dependencies listed in `go.mod`. ## Running the Application To run the application, use the following command: ```bash go run main.go ``` The application will start a web server on `http://localhost:8080`. You can access the following routes: - `/`: The homepage, rendered using `index.tmpl`. - `/foo`: The "Foo" page, rendered using `bar.tmpl`. - `/public/assets/images/example.png`: An example image served from the embedded assets. - `/favicon.ico`: The favicon served from the embedded assets. ## Embedding Files The `//go:embed` directive is used to embed the contents of the `assets` and `templates` directories into the Go binary. The embedded files are accessed using the `embed.FS` type. Example usage in `main.go`: ```go //go:embed assets/* templates/* var f embed.FS func main() { router := gin.Default() templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl")) router.SetHTMLTemplate(templ) router.StaticFS("/public", http.FS(f)) router.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "title": "Main website", }) }) router.GET("/foo", func(c *gin.Context) { c.HTML(http.StatusOK, "bar.tmpl", gin.H{ "title": "Foo website", }) }) router.GET("favicon.ico", func(c *gin.Context) { file, _ := f.ReadFile("assets/favicon.ico") c.Data( http.StatusOK, "image/x-icon", file, ) }) router.Run(":8080") } ``` ## License This project is licensed under the MIT License. See the [LICENSE](../LICENSE) file for details. ## Contributing Contributions are welcome! Please see the [CONTRIBUTING](../CONTRIBUTING.md) file for guidelines. ## References - [Go 1.16 Release Notes](https://tip.golang.org/doc/go1.16#embed) - [embed package documentation](https://tip.golang.org/pkg/embed/) --- ## File: cookie/README.md # Cookie Example This example demonstrates how to set and get cookies using the Gin framework. ## Steps to Run the Example 1. **Build and Run the Server:** ```bash go run main.go ``` 1. **Login to Set the Cookie:** Open your browser and visit the login page: ```sh http://localhost:8080/login ``` 1. **Access the Home Page within 30 Seconds:** After logging in, visit the home page within 30 seconds to see the cookie in action: ```sh http://localhost:8080/home ``` 1. **Access the Home Page after 30 Seconds:** If you try to visit the home page after 30 seconds, you will see a forbidden error due to the expired cookie: ```sh http://localhost:8080/home ``` ## Code Explanation - **main.go:** - The `main.go` file contains the server setup and route definitions. - The `/login` route sets a cookie with a label "ok" and a max age of 30 seconds. - The `/home` route is protected by the `CookieTool` middleware, which checks for the presence of the cookie. ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func CookieTool() gin.HandlerFunc { return func(c *gin.Context) { // Get cookie if cookie, err := c.Cookie("label"); err == nil { if cookie == "ok" { c.Next() return } } // Cookie verification failed c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden with no cookie"}) c.Abort() } } func main() { route := gin.Default() route.GET("/login", func(c *gin.Context) { // Set cookie {"label": "ok" }, maxAge 30 seconds. c.SetCookie("label", "ok", 30, "/", "localhost", false, true) c.String(200, "Login success!") }) route.GET("/home", CookieTool(), func(c *gin.Context) { c.JSON(200, gin.H{"data": "Your home page"}) }) route.Run(":8080") } ``` ## Conclusion This example shows how to use cookies for simple session management in a Gin web application. By following the steps above, you can see how cookies are set and validated in a real-world scenario. --- ## File: forward-proxy/README.md # A proxy integrate both forward and reverse Run the server and make following reqeust to test forward function. Remember to set `forward=ok` in the header so the middleware can tell which one is for forward and which one is for reverse. The demo can be adapted to puer forward proxy. ```python import requests def test_forward(): res=requests.get("http://www.baidu.com",headers={"forward":"ok"},proxies={"http":"http://127.0.0.1:8888"}) print (res.text) test_forward() ``` --- ## File: graceful-shutdown/graceful-shutdown/README.md # Graceful Shutdown Examples This directory contains examples demonstrating how to implement graceful shutdowns in a Gin server using context with and without context. ## Project Structure - `notify-with-context/`: Example of graceful shutdown using context. - `notify-without-context/`: Example of graceful shutdown without using context. ## Usage ### Notify with Context 1. Install the required dependencies: ```bash go get -u github.com/gin-gonic/gin ``` 2. Run the server: ```bash go run notify-with-context/server.go ``` 3. Access the server at `http://localhost:8080/`. 4. To trigger a graceful shutdown, send an interrupt signal (e.g., `Ctrl+C` in the terminal). The server will complete any ongoing requests before shutting down. ### Notify without Context 1. Install the required dependencies: ```bash go get -u github.com/gin-gonic/gin ``` 2. Run the server: ```bash go run notify-without-context/server.go ``` 3. Access the server at `http://localhost:8080/`. 4. To trigger a graceful shutdown, send an interrupt signal (e.g., `Ctrl+C` in the terminal). The server will complete any ongoing requests before shutting down. ## Code Explanation ### Notify with Context Example - The server is initialized with a simple route that simulates a delay of 10 seconds. - A context is created that listens for interrupt signals. - When an interrupt signal is received, the server is shut down gracefully using the context. ### Notify without Context Example - The server is initialized with a simple route that simulates a delay of 5 seconds. - A channel is created to listen for interrupt signals. - When an interrupt signal is received, the server is shut down gracefully using the `server.Shutdown()` method with a timeout context. --- ## File: graceful-shutdown/close/README.md # Graceful Shutdown Example - Close Method This example demonstrates how to implement a graceful shutdown in a Gin server using the `server.Close()` method. ## Project Structure - `server.go`: The main server implementation that handles graceful shutdown. ## Usage 1. Install the required dependencies: ```bash go get -u github.com/gin-gonic/gin ``` 2. Run the server: ```bash go run server.go ``` 3. Access the server at `http://localhost:8080/`. 4. To trigger a graceful shutdown, send an interrupt signal (e.g., `Ctrl+C` in the terminal). The server will complete any ongoing requests before shutting down. ## Code Explanation - The server is initialized with a simple route that simulates a delay of 5 seconds. - A channel is created to listen for interrupt signals. - When an interrupt signal is received, the server is closed gracefully using the `server.Close()` method. --- ## File: group-routes/README.md ### Group routes This example shows how to group different routes in their own files and group them together in a orderly manner like this: ```go func getRoutes() { v1 := router.Group("/v1") addUserRoutes(v1) addPingRoutes(v1) v2 := router.Group("/v2") addPingRoutes(v2) } ``` --- ## File: grpc/example1/README.md # gRPC Example This guide gets you started with gRPC in Go with a simple working example. ## Prerequisites Install the protocol compiler plugins for Go using the following commands: ```sh go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28 go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2 ``` Update your `PATH` so that the `protoc` compiler can find the plugins: ```sh export PATH="$PATH:$(go env GOPATH)/bin" ``` ## Regenerate gRPC code ```sh protoc --go_out=gen --go_opt=paths=source_relative \ --go-grpc_out=gen --go-grpc_opt=paths=source_relative \ -I=$PWD pb/helloworld.proto ``` ## Running First Step: run grpc server ```sh go run grpc/server.go ``` Second Step: run gin server ```sh go run gin/main.go ``` ## Testing Send data to gin server: ```sh curl -v 'http://localhost:8080/rest/n/gin' ``` or using [grpcurl](https://github.com/fullstorydev/grpcurl) command: ```sh grpcurl -d '{"name": "gin"}' \ -plaintext localhost:50051 helloworld.v1.Greeter/SayHello ``` --- ## File: http2/README.md ## How to generate RSA private key and digital certificate 1. Install Openssl Please visit https://github.com/openssl/openssl to get pkg and install. 2. Generate RSA private key ```sh $ mkdir testdata $ openssl genrsa -out ./testdata/server.key 2048 ``` 3. Generate digital certificate ```sh $ openssl req -new -x509 -key ./testdata/server.key -out ./testdata/server.pem -days 365 ``` ## 2. Official Technical Reference & Guides (gin-gonic/website) # Gin website [](https://github.com/gin-gonic/website/actions/workflows/node.yml) [](https://github.com/gin-gonic/website/actions/workflows/trivy-scan.yml) Welcome! This repository houses all the assets required to build the Gin website and documentation. We're pleased that you want to contribute! The website is hosted at [https://gin-gonic.com](https://gin-gonic.com). We use [Astro](https://astro.build) to format and generate our website, the [Starlight](https://starlight.astro.build) template for styling and site structure. Thanks!. ## Contribution - Fork the repository You can click the Fork button in the upper-right area of the screen to create a copy of this repository in your GitHub account. This copy is called as fork. - Create one pull request Make any changes you want in your fork, and when you are ready to send those changes to us, go to your fork and create a new pull request to let us know about it. - Merge the pull request Once your pull request is created, a Gin reviewer will take responsibility for providing clear, actionable feedback, re-improve and merge. ## Running See the [official Astro documentation](https://docs.astro.build/en/getting-started) for Astro installation instructions. and [Starlight documentation](https://starlight.astro.build/getting-started) for Starlight installation instructions. To run the site locally when you have Hugo installed: ```sh git clone https://github.com//website.git # your fork url cd website # ensure you have node installed node -v # else https://nodejs.org/en/download npm install npm run dev ``` This will start the local Astro server on port 4321. Open up your browser to to view the site. As you make changes to the source files, Astro updates the site and forces a browser refresh. ## 🚀 Project Structure Inside of your Astro + Starlight project, you'll see the following folders and files: ```bash . ├── public/ ├── src/ │ ├── assets/ │ ├── content/ │ │ ├── docs/ │ └── content.config.ts ├── astro.config.mjs ├── package.json └── tsconfig.json ``` Starlight looks for `.md` or `.mdx` files in the `src/content/docs/` directory. Each file is exposed as a route based on its file name. Images can be added to `src/assets/` and embedded in Markdown with a relative link. Static assets, like favicons, can be placed in the `public/` directory. ## 🧞 Commands All commands are run from the root of the project, from a terminal: | Command | Action | | :------------------------ | :----------------------------------------------- | | `npm install` | Installs dependencies | | `npm run dev` | Starts local dev server at `localhost:4321` | | `npm run build` | Build your production site to `./dist/` | | `npm run preview` | Preview your build locally, before deploying | | `npm run astro ...` | Run CLI commands like `astro add`, `astro check` | | `npm run astro -- --help` | Get help using the Astro CLI | ## Thanks Gin thrives on community participation, and we really appreciate your contributions to our site and our documentation!