在使用Gin框架提供Web接口时,可以通过获取请求的Host字段来判断不同的操作。下面是一个简单的示例代码:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
host := c.Request.Host
if host == "example.com" {
c.String(http.StatusOK, "Hello from example.com")
} else if host == "api.example.com" {
c.String(http.StatusOK, "Hello from api.example.com")
} else {
c.String(http.StatusOK, "Unknown host")
}
})
router.Run(":8080")
}
在上述示例中,当访问根路径”/“时,通过比较请求的Host字段来确定执行不同的操作。你可以根据实际需求修改相应的逻辑。
内容由零声教学AI助手提供,问题来源于学员提问