创建开发用户和组

  1. # 创建应用开发组
  2. groupadd -g 5000 appgroup
  3. # 创建开发用户
  4. useradd -g 5000 -u 5000 appuser
  5. # 设置用户密码
  6. passwd appuser << EOF
  7. appuser
  8. appuser
  9. EOF
  10. # 切换到 appuser 用户
  11. su - appuser
  12. # 在 appuser 用户下创建 IDE 目录
  13. mkdir -p ~/golang/ide

配置 Go 环境变量(appuser 用户下)

  1. # 修改环境变量
  2. vim ~/.bash_profile
  3. export GOROOT=/usr/local/go
  4. export PATH=$GOROOT/bin:.:$PATH
  5. # 文件生效
  6. source ~/.bash_profile
  7. # 检查 Go 版本
  8. go version

安装配置 IDE 工具(GoLand)

  1. # 上传 GoLand 工具到 /soft
  2. # 解压 GoLand 工具
  3. cd ~/golang/ide/
  4. tar -xzvf /soft/goland-2020.2.2.tar.gz
  5. # 改名解压文件
  6. mv GoLand-2020.2.2/ goland
  7. # 修改环境变量
  8. vim ~/.bash_profile
  9. export GOROOT=/usr/local/go
  10. export JAVA_HOME=/usr/local/jdk8
  11. export CLASSPATH=$JAVA_HOME/li:.
  12. export PATH=$JAVA_HOME/bin:/home/appuser/golang/ide/goland/bin:$GOROOT/bin:.:$PATH
  13. export DISPLAY=:0

启动 GoLand

允许打开图行界面窗口(root 用户下)

  1. xhost +

新建窗口,启动安装程序:goland.sh (appuser 用户下)

配置并使用 Gin 框架 - 图1

配置并使用 Gin 框架 - 图2

配置并使用 Gin 框架 - 图3

配置并使用 Gin 框架 - 图4

配置并使用 Gin 框架 - 图5

新建测试项目

  • 创建项目工作空间

    1. su - appuser
    2. mkdir -p ~/golang/workspace
  • 生成模块文件

    1. cd ~/golang/workspace/demo1/
    2. go mod init demo1
  • 创建项目 demo1

配置并使用 Gin 框架 - 图6

  • 测试项目

配置并使用 Gin 框架 - 图7

使用 Gin 框架

  • webserver.go

    1. package main
    2. import (
    3. "fmt"
    4. "github.com/gin-gonic/gin"
    5. "net/http"
    6. )
    7. func main() {
    8. fmt.Println("web server")
    9. webserver := gin.Default()
    10. webserver.StaticFS("/public", http.Dir("html"))
    11. webserver.GET("/getUsers", func(context *gin.Context) {
    12. fmt.Println("web server1")
    13. // name := context.Query("name")
    14. // password := context.Query("password")
    15. name := context.Request.FormValue("userName")
    16. password := context.Request.FormValue("pass")
    17. fmt.Println("name:", name, "\tpassword:", password)
    18. context.JSON(200, gin.H{
    19. "user": "Jim",
    20. })
    21. })
    22. webserver.POST("/login", func(context *gin.Context) {
    23. fmt.Println("web server1")
    24. // name := context.Query("name")
    25. // password := context.Query("password")
    26. name := context.Request.PostFormValue("userName")
    27. password := context.Request.PostFormValue("pass")
    28. fmt.Println("name:", name, "\tpassword:", password)
    29. context.JSON(200, gin.H{
    30. "user": "Jim",
    31. })
    32. })
    33. webserver.Run(":9080")
    34. }
  • register.html

配置并使用 Gin 框架 - 图8

  • 运行结果

配置并使用 Gin 框架 - 图9

配置并使用 Gin 框架 - 图10

配置并使用 Gin 框架 - 图11

使用 JSON 渲染

  • 代码 配置并使用 Gin 框架 - 图12

  • 运行结果

配置并使用 Gin 框架 - 图13