How to use Gin to create a web server

Known for its speed and small memory footprint, Gin is one of the most popular and widely used Go web frameworks. It provides features like routing, middleware support, and JSON validation, making it great for building high-performance REST APIs.
 
So, how do we use Gin to create a web server? Here's a step-by-step guide to help you get started:
 

1. First, install Go if you haven't already 

  • install (https://go.dev/)
  
  • set up Go environment variables(Windows)
    The default installation directory is C:\Program Files\Go

    Right-click➡️Personalize➡️system➡️about➡️Advanced system settings➡️Environment Variables➡️system variables section

    Create a new system variable named GOROOT with the value C:\Program Files\Go.

    Then, add %GOROOT%\bin to the Path variable.

  
  • verify the installation
    go version
  
  • configure your GOPROXY(If you're behind a proxy or your network setup requires this, run one of the following commands)
go env -w GOPROXY=https://goproxy.cn,direct
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct
go env -w GOPROXY=https://mirrors.cloud.tencent.com/go,direct
// You can check the current proxy configuration with
go env GOPROXY
// Clear the Go module cache
go clean --modcache

2. Create a new project directory and initialize it:

 
mkdir gin-server 
cd gin-server 
go mod init example.com/gin-server
go get -u github.com/gin-gonic/gin
 

3. Create a main.go file with a basic Gin server:

 
package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run(":8080") // listen and serve on 0.0.0.0:8080
}

 

4. Run the application

  go run main.go

posted @ 2025-02-27 22:07  Ashe|||^_^  阅读(16)  评论(0)    收藏  举报