### Create a Simple Gin Web Application (Go)
Source: https://gin-gonic.com/ja/docs
A basic 'Hello, World!' example demonstrating how to create a Gin router with default middleware, define a GET endpoint, and start the HTTP server. It returns a JSON response upon hitting the '/ping' endpoint.
```go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// loggerとrecoveryミドルウェア付きGinルーター作成
r := gin.Default()
// 簡単なGETエンドポイント定義
r.GET("/ping", func(c *gin.Context) {
// JSONレスポンスを返す
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
// ポート8080でサーバー起動(デフォルト)
// 0.0.0.0:8080(Windowsではlocalhost:8080)で待機
r.Run()
}
```
--------------------------------
### One-Line Let's Encrypt HTTPS Server Setup (Go)
Source: https://gin-gonic.com/ja/docs/examples/support-lets-encrypt
This Go code snippet demonstrates a straightforward way to set up a Let's Encrypt HTTPS server with Gin Gonic. It automatically obtains and renews SSL certificates for the specified domains. Ensure the required packages 'github.com/gin-gonic/autotls' and 'github.com/gin-gonic/gin' are installed.
```go
package main
import (
"log"
"github.com/gin-gonic/autotls"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// Ping handler
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
log.Fatal(autotls.Run(router, "example1.com", "example2.com"))
}
```
--------------------------------
### GET /user/:name/*action
Source: https://gin-gonic.com/ja/docs/examples/param-in-path
This endpoint matches URLs like /user/john/ and /user/john/send. It captures both a 'name' and a wildcard 'action' parameter from the URL path.
```APIDOC
## GET /user/:name/*action
### Description
This endpoint captures a name and a wildcard action from the URL path.
### Method
GET
### Endpoint
/user/:name/*action
### Parameters
#### Path Parameters
- **name** (string) - Required - The name to be captured from the URL.
- **action** (string) - Required - A wildcard path segment capturing the rest of the URL.
### Request Example
```
GET /user/john/send
```
### Response
#### Success Response (200)
- **string** - A message combining the name and action.
#### Response Example
```
john is /send
```
```
--------------------------------
### Install Gin Web Framework (Go)
Source: https://gin-gonic.com/ja/docs
This snippet shows how to import the Gin framework into your Go project. Gin is automatically downloaded during the build process if you are using Go modules.
```go
import "github.com/gin-gonic/gin"
```
--------------------------------
### Run a Gin Application (Shell)
Source: https://gin-gonic.com/ja/docs
This command executes a Go application file named 'main.go'. It's used to start the Gin web server after the code has been written and saved.
```shell
go run main.go
```
--------------------------------
### GET /someProtoBuf
Source: https://gin-gonic.com/ja/docs/examples/rendering
Renders a Protocol Buffers response.
```APIDOC
## GET /someProtoBuf
### Description
Renders a Protocol Buffers response. The data is serialized into binary format.
### Method
GET
### Endpoint
/someProtoBuf
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **Label** (string pointer) - A label string.
- **Reps** (list of int64) - A list of int64 values.
#### Response Example
(Binary data representing serialized protoexample.Test)
```protobuf
// The actual binary response content is not representable as text.
// It conforms to the protoexample.Test definition.
```
```
--------------------------------
### GET /user/:name
Source: https://gin-gonic.com/ja/docs/examples/param-in-path
This endpoint matches URLs like /user/john but not /user/ or /user. It extracts a 'name' parameter from the URL path.
```APIDOC
## GET /user/:name
### Description
This endpoint captures a name from the URL path.
### Method
GET
### Endpoint
/user/:name
### Parameters
#### Path Parameters
- **name** (string) - Required - The name to be captured from the URL.
### Request Example
```
GET /user/john
```
### Response
#### Success Response (200)
- **string** - A greeting message including the captured name.
#### Response Example
```
Hello john
```
```
--------------------------------
### Implement Gin-Gonic Middleware
Source: https://gin-gonic.com/ja/docs/examples/using-middleware
This Go code snippet demonstrates how to implement and apply middleware in Gin-Gonic. It shows the creation of a router, the addition of global middleware (Logger and Recovery), and the configuration of middleware for specific routes and groups. Ensure Gin-Gonic is imported.
```go
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// デフォルトのミドルウェアが何もない router を作成する
router := gin.New()
// グローバルなミドルウェア
// Logger ミドルウェアは GIN_MODE=release を設定してても、 gin.DefaultWriter にログを出力する
// gin.DefaultWriter はデフォルトでは os.Stdout。
router.Use(gin.Logger())
// Recovery ミドルウェアは panic が発生しても 500 エラーを返してくれる
router.Use(gin.Recovery())
// 個別のルーティングに、ミドルウェアを好きに追加することもできる
router.GET("/benchmark", MyBenchLogger(), benchEndpoint)
// 認証が必要なグループ
// authorized := router.Group("/", AuthRequired())
// 下記と同一
authorized := router.Group("/")
// 個別のグループのミドルウェア。この例では、AuthRequired() ミドルウェアを認証が必要なグループに設定している。
authorized.Use(AuthRequired())
{
authorized.POST("/login", loginEndpoint)
authorized.POST("/submit", submitEndpoint)
authorized.POST("/read", readEndpoint)
// ネストしたグループ
testing := authorized.Group("testing")
testing.GET("/analytics", analyticsEndpoint)
}
// 0.0.0.0:8080 でサーバーを立てる
router.Run(":8080")
}
// Dummy functions for compilation
func MyBenchLogger() gin.HandlerFunc {
return func(c *gin.Context) {
// Implementation for MyBenchLogger
c.Next()
}
}
func benchEndpoint(c *gin.Context) {
c.JSON(200, gin.H{
"message": "benchmark"
})
}
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
// Implementation for AuthRequired
c.Next()
}
}
func loginEndpoint(c *gin.Context) {
c.JSON(200, gin.H{
"message": "login"
})
}
func submitEndpoint(c *gin.Context) {
c.JSON(200, gin.H{
"message": "submit"
})
}
func readEndpoint(c *gin.Context) {
c.JSON(200, gin.H{
"message": "read"
})
}
func analyticsEndpoint(c *gin.Context) {
c.JSON(200, gin.H{
"message": "analytics"
})
}
```
--------------------------------
### HTTP Redirects (GET)
Source: https://gin-gonic.com/ja/docs/examples/redirects
Demonstrates how to perform a permanent HTTP redirect to an external URL using the `Redirect` method on a GET request.
```APIDOC
## GET /test (Redirect to External URL)
### Description
Performs a permanent HTTP redirect to an external URL.
### Method
GET
### Endpoint
/test
### Parameters
None
### Request Example
```
router.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
})
```
### Response
#### Success Response (301 Moved Permanently)
Redirects to `http://www.google.com/`.
#### Response Example
```
(HTTP 301 response)
```
```
--------------------------------
### POST /upload
Source: https://gin-gonic.com/ja/docs/examples/upload-file/single-file
This endpoint allows clients to upload a single file. The file is received as part of a multipart form data request. The server saves the uploaded file to a specified directory.
```APIDOC
## POST /upload
### Description
This endpoint handles the upload of a single file sent via multipart/form-data. It saves the uploaded file to the `./files/` directory on the server. The filename is extracted from the form data.
### Method
POST
### Endpoint
/upload
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **file** (file) - Required - The file to be uploaded, sent as part of the multipart form data.
### Request Example
```curl
curl -X POST http://localhost:8080/upload \
-F "file=@/Users/appleboy/test.zip" \
-H "Content-Type: multipart/form-data"
```
### Response
#### Success Response (200)
- **message** (string) - A confirmation message indicating the file was uploaded successfully.
#### Response Example
```json
{
"message": "'test.zip' uploaded!"
}
```
```
--------------------------------
### Ginのインストールとプロジェクト初期化 (Go)
Source: https://gin-gonic.com/ja/docs/quickstart
Ginフレームワークをインストールし、Goプロジェクトを初期化する手順です。まずプロジェクトディレクトリを作成し、`go mod init`でモジュールを初期化後、`go get`でGinパッケージを取得します。
```bash
mkdir gin-quickstart && cd gin-quickstart
go mod init gin-quickstart
go get -u github.com/gin-gonic/gin
```
--------------------------------
### GET /json
Source: https://gin-gonic.com/ja/docs/examples/pure-json
This endpoint demonstrates the default behavior of Gin's JSON method, which escapes HTML characters.
```APIDOC
## GET /json
### Description
This endpoint returns a JSON response where HTML characters like '<' and '>' are escaped into their Unicode equivalents (e.g., `\u003c`). This is the default behavior for security and proper JSON formatting.
### Method
GET
### Endpoint
/json
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **html** (string) - The HTML string with escaped characters.
#### Response Example
```json
{
"html": "<\/b>Hello, world!<\/b>"
}
```
```
--------------------------------
### Handle Form Post with Query String in Gin Gonic (Go)
Source: https://gin-gonic.com/ja/docs/examples/query-and-post-form
This Go code snippet shows how to define a POST route in Gin Gonic that accepts both query parameters and form data. It uses `c.Query()` to get query parameters and `c.PostForm()` to retrieve form fields. The `c.DefaultQuery()` function provides a default value if the query parameter is not present. The example handler extracts 'id', 'page', 'name', and 'message' and prints them. It assumes the server is running on port 8080.
```go
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.POST("/post", func(c *gin.Context) {
id := c.Query("id")
page := c.DefaultQuery("page", "0")
name := c.PostForm("name")
message := c.PostForm("message")
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
})
router.Run(":8080")
}
```
--------------------------------
### Gin Router Setup with Custom Middlewares
Source: https://gin-gonic.com/ja/blog/news/how-to-build-one-effective-middleware
This Go code sets up a Gin router and applies multiple custom middleware functions. It includes global middleware and route-specific middleware, demonstrating how they are registered and executed in sequence.
```go
func main() {
router := gin.Default()
router.Use(globalMiddleware())
router.GET("/rest/n/api/*some", mid1(), mid2(), handler)
router.Run()
}
func globalMiddleware() gin.HandlerFunc {
fmt.Println("globalMiddleware...1")
return func(c *gin.Context) {
fmt.Println("globalMiddleware...2")
c.Next()
fmt.Println("globalMiddleware...3")
}
}
func handler(c *gin.Context) {
fmt.Println("exec handler.")
}
func mid1() gin.HandlerFunc {
fmt.Println("mid1...1")
return func(c *gin.Context) {
fmt.Println("mid1...2")
c.Next()
fmt.Println("mid1...3")
}
}
func mid2() gin.HandlerFunc {
fmt.Println("mid2...1")
return func(c *gin.Context) {
fmt.Println("mid2...2")
c.Next()
fmt.Println("mid2...3")
}
}
```
--------------------------------
### GET /someXML
Source: https://gin-gonic.com/ja/docs/examples/rendering
Renders a simple XML response with a message and status.
```APIDOC
## GET /someXML
### Description
Renders a simple XML response with a message and status.
### Method
GET
### Endpoint
/someXML
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **message** (string) - A success message.
- **status** (integer) - The HTTP status code.
#### Response Example
```xml
```
```
--------------------------------
### Render HTML with nested directories using LoadHTMLGlob
Source: https://gin-gonic.com/ja/docs/examples/html-rendering
This example shows how to load HTML templates from nested directories using `LoadHTMLGlob`. It allows you to organize templates in subdirectories and access them by their relative path. Remember to define templates using `{{define ""}}` for proper parsing.
```Go
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/**/*")
router.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
"title": "Posts",
})
})
router.GET("/users/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
"title": "Users",
})
})
router.Run(":8080")
}
```
--------------------------------
### Test File Upload with Curl
Source: https://gin-gonic.com/ja/docs/examples/upload-file/single-file
This is a command-line instruction using `curl` to test the file upload endpoint configured in the Gin Gonic application. It sends a POST request with a file and sets the appropriate Content-Type header for multipart/form-data.
```bash
curl -X POST http://localhost:8080/upload \
-F "file=@/Users/appleboy/test.zip" \
-H "Content-Type: multipart/form-data"
```
--------------------------------
### Graceful Shutdown with Go 1.8+ http.Server.Shutdown()
Source: https://gin-gonic.com/ja/docs/examples/graceful-restart-or-stop
This example utilizes Go 1.8's built-in `http.Server.Shutdown()` method for graceful shutdowns. It listens for interrupt and termination signals (SIGINT, SIGTERM) and initiates a 5-second shutdown timeout. This approach avoids external dependencies for graceful shutdowns.
```go
//go:build go1.8
// +build go1.8
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
time.Sleep(5 * time.Second)
c.String(http.StatusOK, "Welcome Gin Server")
})
srv := &http.Server{
Addr: ":8080",
Handler: router.Handler(),
}
go func() {
// service connections
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// シグナル割り込みを待ち、5秒間のタイムアウトでサーバーを正常終了
quit := make(chan os.Signal, 1)
// kill(引数なし)は既定で syscall.SIGTERM を送ります
// kill -2 は syscall.SIGINT です
// kill -9 は syscall.SIGKILL ですが捕捉できないため、追加する必要がありません
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Println("Server Shutdown:", err)
}
log.Println("Server exiting")
}
```
--------------------------------
### GET /someYAML
Source: https://gin-gonic.com/ja/docs/examples/rendering
Renders a simple YAML response with a message and status.
```APIDOC
## GET /someYAML
### Description
Renders a simple YAML response with a message and status.
### Method
GET
### Endpoint
/someYAML
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **message** (string) - A success message.
- **status** (integer) - The HTTP status code.
#### Response Example
```yaml
message: hey
status: 200
```
```
--------------------------------
### Gin Gonic: Define routes with path parameters
Source: https://gin-gonic.com/ja/docs/examples/param-in-path
This Go code snippet shows how to define routes in Gin Gonic that capture parameters from the URL path. It uses `router.GET` with placeholders like `:name` and `*action`. The captured parameters can be accessed using `c.Param()` within the handler function. This is useful for creating dynamic API endpoints.
```go
func main() {
router := gin.Default()
// このハンドラは /user/john にはマッチするが、/user/ や /user にはマッチしない
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// しかし、下記は /user/john/ と /user/john/send にマッチする
// もしほかのルーターが /user/john にマッチしなければ、/user/john/ にリダイレクトしてくれる
router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
router.Run(":8080")
}
```
--------------------------------
### Render YAML with Gin Gonic
Source: https://gin-gonic.com/ja/docs/examples/rendering
This example demonstrates serving YAML content with Gin Gonic. The `c.YAML` function is used to serialize a Go data structure (like `gin.H`) into YAML format and send it as the HTTP response. The Content-Type header is automatically set to `application/yaml`.
```Go
func main() {
router := gin.Default()
// ... other routes ...
router.GET("/someYAML", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
// ... other routes ...
// 0.0.0.0:8080 でサーバーを立てます。
router.Run(":8080")
}
```
--------------------------------
### Set custom delimiters for HTML templates
Source: https://gin-gonic.com/ja/docs/examples/html-rendering
This example demonstrates how to customize the delimiters used in your HTML templates. By calling `router.Delims()`, you can specify custom opening and closing delimiters, which then need to be used in your template files.
```Go
router := gin.Default()
router.Delims("{[{", "}]}")
router.LoadHTMLGlob("/path/to/templates")
```
--------------------------------
### Configure Gin Server Port and Mode
Source: https://gin-gonic.com/ja/docs/deployment
Demonstrates how to configure the Gin server's port and operating mode using environment variables or code. The PORT environment variable sets the listening port for router.Run(), and GIN_MODE controls debug output. Code examples show default port binding, custom port/address binding, and listening only on a port.
```Go
import "github.com/gin-gonic/gin"
func main() {
// Binds to all interfaces and port 8080 by default if no arguments are provided to Run().
// The PORT environment variable can be used to change the listen port if Run() is used without arguments.
router := gin.Default()
router.Run()
// Specifies the bind address and port.
router := gin.Default()
router.Run("192.168.1.100:8080")
// Specifies only the listen port. It will be bound to all interfaces.
router := gin.Default()
router.Run(":8080")
}
```
--------------------------------
### Gin Gonic Async Goroutine Context Copy
Source: https://gin-gonic.com/ja/docs/examples/goroutines-inside-a-middleware
This example shows how to properly create a copy of the Gin context before launching a new goroutine. This ensures that the goroutine can safely access request-related information without being affected by the cancellation of the original request context. It uses `c.Copy()` to create a detached context for the goroutine.
```go
func main() {
router := gin.Default()
router.GET("/long_async", func(c *gin.Context) {
// goroutine 内で使用するコピーを生成します
cCp := c.Copy()
go func() {
// time.Sleep() を使って、長時間かかる処理をシミュレートします。5秒です。
time.Sleep(5 * time.Second)
// コピーされた context である "cCp" を使ってください。重要!
log.Println("Done! in path " + cCp.Request.URL.Path)
}()
})
router.GET("/long_sync", func(c *gin.Context) {
// time.Sleep() を使って、長時間かかる処理をシミュレートします。5秒です。
time.Sleep(5 * time.Second)
// goroutine を使ってなければ、context をコピーする必要はありません。
log.Println("Done! in path " + c.Request.URL.Path)
})
// 0.0.0.0:8080 でサーバーを立てます。
router.Run(":8080")
}
```
--------------------------------
### Run Multiple Services with Gin and errgroup (Go)
Source: https://gin-gonic.com/ja/docs/examples/run-multiple-service
This Go code snippet demonstrates how to run multiple HTTP services concurrently using the Gin web framework and the `errgroup` package. It defines two separate Gin routers and starts them as independent servers, managed by `errgroup.Group` for graceful error handling and shutdown.
```Go
package main
import (
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
)
var (
g errgroup.Group
)
func router01() http.Handler {
e := gin.New()
e.Use(gin.Recovery())
e.GET("/", func(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": http.StatusOK,
"error": "Welcome server 01",
},
)
})
return e
}
func router02() http.Handler {
e := gin.New()
e.Use(gin.Recovery())
e.GET("/", func(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": http.StatusOK,
"error": "Welcome server 02",
},
)
})
return e
}
func main() {
server01 := &http.Server{
Addr: ":8080",
Handler: router01(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
server02 := &http.Server{
Addr: ":8081",
Handler: router02(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
g.Go(func() error {
return server01.ListenAndServe()
})
g.Go(func() error {
return server02.ListenAndServe()
})
if err := g.Wait(); err != nil {
log.Fatal(err)
}
}
```
--------------------------------
### Handle Single File Upload with Gin Gonic
Source: https://gin-gonic.com/ja/docs/examples/upload-file/single-file
This Go code snippet shows how to set up a Gin Gonic web server to handle single file uploads. It configures the maximum memory for multipart forms and defines a POST endpoint to receive and save uploaded files. The `file.Filename` should not be trusted directly due to security concerns.
```go
func main() {
router := gin.Default()
// マルチパートフォームが利用できるメモリの制限を設定する(デフォルトは 32 MiB)
router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// 単一のファイル
file, _ := c.FormFile("file")
log.Println(file.Filename)
// 特定のディレクトリにファイルをアップロードする
c.SaveUploadedFile(file, "./files/" + file.Filename)
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
})
router.Run(":8080")
}
```
--------------------------------
### GET /purejson
Source: https://gin-gonic.com/ja/docs/examples/pure-json
This endpoint uses the PureJSON method to return HTML characters without escaping.
```APIDOC
## GET /purejson
### Description
This endpoint utilizes Gin's `PureJSON` method to return a JSON response where HTML characters are encoded directly, without escaping. This is useful when you intentionally want to include raw HTML within your JSON payload. Note that this feature is not available in Go versions 1.6 and below.
### Method
GET
### Endpoint
/purejson
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **html** (string) - The raw HTML string.
#### Response Example
```json
{
"html": "Hello, world!"
}
```
```
--------------------------------
### Implement Basic Authentication with Gin Gonic Middleware
Source: https://gin-gonic.com/ja/docs/examples/using-basicauth-middleware
This Go code uses the Gin Gonic framework to set up a web server with a protected route using the BasicAuth middleware. The middleware authenticates users based on provided username-password pairs. If authentication is successful, it allows access to the '/admin/secrets' endpoint, which then displays user-specific secret data. Dependencies include the 'gin-gonic/gin' package and the 'net/http' package for HTTP status codes.
```go
// 秘匿されたデータをシミュレートする
var secrets = gin.H{
"foo": gin.H{"email": "foo@bar.com", "phone": "123433"},
"austin": gin.H{"email": "austin@example.com", "phone": "666"},
"lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
}
func main() {
router := gin.Default()
// gin.BasicAuth() ミドルウェアを使用したグループ
// gin.Accounts は map[string]string へのショートカットです。
authorized := router.Group("/admin", gin.BasicAuth(gin.Accounts{
"foo": "bar",
"austin": "1234",
"lena": "hello2",
"manu": "4321",
}))
// /admin/secrets エンドポイントは localhost:8080/admin/secrets です。
authorized.GET("/secrets", func(c *gin.Context) {
// BasicAuth ミドルウェアで設定されたユーザー名にアクセスします。
user := c.MustGet(gin.AuthUserKey).(string)
if secret, ok := secrets[user]; ok {
c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
} else {
c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
}
})
// 0.0.0.0:8080 でサーバーを立てます。
router.Run(":8080")
}
```
--------------------------------
### Build Single Binary with Templates in Go
Source: https://gin-gonic.com/ja/docs/examples/bind-single-binary-with-template
This Go code snippet demonstrates how to use the 'go-assets' package to embed templates directly into a single executable binary. It initializes a Gin router, loads templates from embedded assets, and defines a route to render an HTML template. Dependencies include the 'gin-gonic/gin' and 'go-assets-builder' packages.
```go
package main
import (
"html/template"
"io/ioutil"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// Assets is a placeholder for the embedded assets. In a real scenario, this would be populated by go-assets-builder.
var Assets = &assetFS{}
func main() {
r := gin.New()
t, err := loadTemplate()
if err != nil {
panic(err)
}
r.SetHTMLTemplate(t)
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "/html/index.tmpl", nil)
})
r.Run(":8080")
}
// loadTemplate loads the templates embedded by go-assets-builder.
func loadTemplate() (*template.Template, error) {
t := template.New("")
for name, file := range Assets.Files {
if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {
continue
}
h, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
t, err = t.New(name).Parse(string(h))
if err != nil {
return nil, err
}
}
return t, nil
}
// assetFS is a mock implementation of an asset file system for demonstration.
// In a real project, this would be generated by go-assets-builder.
type assetFS struct {
Files map[string]*assetInfo
}
type assetInfo struct {
IsDir bool
Content []byte
}
func (a *assetFS) Open(name string) (http.File, error) {
// This is a simplified mock and doesn't implement the http.File interface fully.
// For a real implementation, you would need to return a proper http.File.
if info, ok := a.Files[name]; ok {
return &mockFile{info: info},
nil
}
return nil, fmt.Errorf("file not found: %s", name)
}
// Mock implementation of http.File
type mockFile struct {
info *assetInfo
closed bool
}
func (f *mockFile) Read(p []byte) (n int, err error) {
if f.closed {
return 0, fmt.Errorf("file is closed")
}
copy(p, f.info.Content)
return len(f.info.Content), io.EOF // Simplified: returns all content and EOF
}
func (f *mockFile) Seek(offset int64, whence int) (int64, error) {
// Not implemented for this mock
return 0, errors.New("Seek not implemented")
}
func (f *mockFile) Close() error {
f.closed = true
return nil
}
func (f *mockFile) Readdir(count int) ([]os.FileInfo, error) {
// Not implemented for this mock
return nil, errors.New("Readdir not implemented")
}
func (f *mockFile) Stat() (os.FileInfo, error) {
// Not implemented for this mock
return nil, errors.New("Stat not implemented")
}
func (f *mockFile) Name() string {
// Not implemented for this mock
return ""
}
func (f *mockFile) Size() int64 {
return int64(len(f.info.Content))
}
func (f *mockFile) Mode() os.FileMode {
// Not implemented for this mock
return 0
}
func (f *mockFile) ModTime() time.Time {
// Not implemented for this mock
return time.Time{}
}
func (f *mockFile) IsDir() bool {
return f.info.IsDir
}
func (f *mockFile) Sys() interface{} {
// Not implemented for this mock
return nil
}
// You would typically use go-assets-builder to generate the Assets variable.
// For example, run `go-assets-builder -source=./static -output=packed.go`
// And then import the generated package.
// For demonstration purposes, we manually define a sample structure.
func init() {
Assets.Files = make(map[string]*assetInfo)
// Assuming you have a template file at ./html/index.tmpl
Assets.Files["/html/index.tmpl"] = &assetInfo{
IsDir: false,
Content: []byte("Hello, {{.Title}}!
"),
}
}
// Dummy imports to satisfy the compiler for the mock functions
import (
"errors"
"fmt"
"io"
"os"
"time"
)
```
--------------------------------
### Gin Middleware Initialization and Request Handling
Source: https://gin-gonic.com/ja/blog/news/how-to-build-one-effective-middleware
This Go code demonstrates the creation of a Gin middleware function. It separates initialization logic (executed once) from request-handling logic (executed per request). The initialization part checks parameters, and the request part sets a value in the context.
```go
func funcName(params string) gin.HandlerFunc {
// <---
// ここが第1部
// --->
// 初期化例:入力パラメータの検証
if err := check(params); err != nil {
panic(err)
}
return func(c *gin.Context) {
// <---
// ここが第2部
// --->
// リクエストごとの実行例:コンテキストへ注入
c.Set("TestVar", params)
c.Next()
}
}
```
--------------------------------
### Ginサンプルコードのダウンロード (Bash)
Source: https://gin-gonic.com/ja/docs/quickstart
Ginの基本的なサンプルコードを`main.go`ファイルとしてダウンロードするためのコマンドです。`curl`コマンドを使用して、指定されたURLからコードを取得し、カレントディレクトリに保存します。
```bash
curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go
```
--------------------------------
### GET /someJSON
Source: https://gin-gonic.com/ja/docs/examples/rendering
Renders a simple JSON response with a message and status.
```APIDOC
## GET /someJSON
### Description
Renders a simple JSON response with a message and status.
### Method
GET
### Endpoint
/someJSON
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **message** (string) - A success message.
- **status** (integer) - The HTTP status code.
#### Response Example
```json
{
"message": "hey",
"status": 200
}
```
```
--------------------------------
### 基本的なGinアプリケーションの作成 (Go)
Source: https://gin-gonic.com/ja/docs/quickstart
Ginフレームワークを使用して、`/ping`エンドポイントで"pong"を返す基本的なAPIサーバを作成します。`gin.Default()`でルーターを初期化し、`GET`メソッドでルートを定義後、`router.Run()`でサーバを起動します。
```go
package main
import "github.com/gin-gonic/gin"
func main() {
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
router.Run() // デフォルトで0.0.0.0:8080で待機します
}
```
--------------------------------
### GET /moreJSON
Source: https://gin-gonic.com/ja/docs/examples/rendering
Renders a JSON response from a struct, demonstrating field name mapping.
```APIDOC
## GET /moreJSON
### Description
Renders a JSON response from a struct, demonstrating field name mapping for the 'Name' field to 'user'.
### Method
GET
### Endpoint
/moreJSON
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **user** (string) - The user's name.
- **Message** (string) - A message from the user.
- **Number** (integer) - An associated number.
#### Response Example
```json
{
"user": "Lena",
"Message": "hey",
"Number": 123
}
```
```
--------------------------------
### GET /:name/:id
Source: https://gin-gonic.com/ja/docs/examples/bind-uri
This endpoint demonstrates binding and validating URI parameters. It expects a 'name' and a 'uuid' in the URL path.
```APIDOC
## GET /:name/:id
### Description
This endpoint binds and validates URI parameters. It expects a 'name' and a 'uuid' in the URL path. The 'id' parameter is expected to be a valid UUID.
### Method
GET
### Endpoint
/:name/:id
### Parameters
#### Path Parameters
- **name** (string) - Required - The name to be bound.
- **id** (string) - Required - The UUID to be bound. Must be a valid UUID format.
### Request Example
```bash
curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
```
### Response
#### Success Response (200)
- **name** (string) - The bound name.
- **uuid** (string) - The bound UUID.
#### Response Example
```json
{
"name": "thinkerou",
"uuid": "987fbc97-4bed-5078-9f07-9141ba07c9f3"
}
```
#### Error Response (400)
- **msg** (object) - An error object detailing the binding or validation failure.
#### Error Response Example
```json
{
"msg": {
"kind": "uri",
"field": "id",
"param": "id",
"type": "uuid.Error",
"value": "not-uuid"
}
}
```
```
--------------------------------
### Implement HTTP/2 Server Push in Go with Gin Gonic
Source: https://gin-gonic.com/ja/docs/examples/http2-server-push
This Go code snippet shows how to enable HTTP/2 Server Push for static assets like JavaScript files. It utilizes the `http.Pusher` interface available from Go 1.8 onwards. The code defines an HTML template and a Gin router that sets up static file serving and HTML templating. When a GET request is made to the root path, it checks if the `http.Pusher` is available and attempts to push the `/assets/app.js` file. The application is then run using TLS on port 8080.
```go
package main
import (
"html/template"
"log"
"github.com/gin-gonic/gin"
)
var html = template.Must(template.New("https").Parse(`
Https Test
Welcome, Ginner!
`))
func main() {
router := gin.Default()
router.Static("/assets", "./assets")
router.SetHTMLTemplate(html)
router.GET("/", func(c *gin.Context) {
if pusher := c.Writer.Pusher(); pusher != nil {
// サーバープッシュするために pusher.Push() を使う
if err := pusher.Push("/assets/app.js", nil); err != nil {
log.Printf("Failed to push: %v", err)
}
}
c.HTML(200, "https", gin.H{
"status": "success",
})
})
// https://127.0.0.1:8080 でサーバーを立てる
router.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")
}
```
--------------------------------
### GET /getd - Bind StructD
Source: https://gin-gonic.com/ja/docs/examples/bind-form-data-request-with-custom-struct
This endpoint illustrates binding form data to a struct (StructD) with an anonymous nested struct.
```APIDOC
## GET /getd
### Description
Binds form data to `StructD`, which includes an anonymous nested struct.
### Method
GET
### Endpoint
/getd
### Query Parameters
- **field_x** (string) - Required - Corresponds to the `FieldX` within the anonymous nested struct.
- **field_d** (string) - Required - Corresponds to `StructD.FieldD`.
### Response
#### Success Response (200)
- **x** (object) - Contains the bound anonymous nested struct data.
- **FieldX** (string) - The value of `field_x`.
- **d** (string) - The value of `field_d`.
### Request Example
```
curl "http://localhost:8080/getd?field_x=hello&field_d=world"
```
### Response Example
```json
{
"d": "world",
"x": {
"FieldX": "hello"
}
}
```
```
--------------------------------
### Custom Autocert Manager for Let's Encrypt HTTPS (Go)
Source: https://gin-gonic.com/ja/docs/examples/support-lets-encrypt
This Go code snippet shows how to configure a Let's Encrypt HTTPS server using a custom autocert manager with Gin Gonic. This approach provides more granular control over certificate policies, including host whitelisting and cache directory. Dependencies include 'github.com/gin-gonic/autotls', 'github.com/gin-gonic/gin', and 'golang.org/x/crypto/acme/autocert'.
```go
package main
import (
"log"
"github.com/gin-gonic/autotls"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/acme/autocert"
)
func main() {
router := gin.Default()
// Ping handler
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
m := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),
Cache: autocert.DirCache("/var/www/.cache"),
}
log.Fatal(autotls.RunWithManager(r, &m))
}
```
--------------------------------
### GET /getb - Bind StructB
Source: https://gin-gonic.com/ja/docs/examples/bind-form-data-request-with-custom-struct
This endpoint demonstrates binding form data to a struct (StructB) that contains a nested struct (StructA).
```APIDOC
## GET /getb
### Description
Binds form data to `StructB`, which includes a nested `StructA`.
### Method
GET
### Endpoint
/getb
### Query Parameters
- **field_a** (string) - Required - Corresponds to `StructA.FieldA`.
- **field_b** (string) - Required - Corresponds to `StructB.FieldB`.
### Response
#### Success Response (200)
- **a** (object) - Contains the bound `StructA` data.
- **FieldA** (string) - The value of `field_a`.
- **b** (string) - The value of `field_b`.
### Request Example
```
curl "http://localhost:8080/getb?field_a=hello&field_b=world"
```
### Response Example
```json
{
"a": {
"FieldA": "hello"
},
"b": "world"
}
```
```
--------------------------------
### GET /getc - Bind StructC
Source: https://gin-gonic.com/ja/docs/examples/bind-form-data-request-with-custom-struct
This endpoint shows how to bind form data to a struct (StructC) containing a pointer to a nested struct (StructA).
```APIDOC
## GET /getc
### Description
Binds form data to `StructC`, which includes a pointer to `StructA`.
### Method
GET
### Endpoint
/getc
### Query Parameters
- **field_a** (string) - Required - Corresponds to `StructA.FieldA` within the `NestedStructPointer`.
- **field_c** (string) - Required - Corresponds to `StructC.FieldC`.
### Response
#### Success Response (200)
- **a** (object | null) - Contains the bound `StructA` data or null if not provided.
- **FieldA** (string) - The value of `field_a`.
- **c** (string) - The value of `field_c`.
### Request Example
```
curl "http://localhost:8080/getc?field_a=hello&field_c=world"
```
### Response Example
```json
{
"a": {
"FieldA": "hello"
},
"c": "world"
}
```
```