Go 开发环境配置

以下方式已不建议使用,使用 Go Module 配置的方式

一、安装 govendor 工具

go get -u github.com/kardianos/govendor

二、创建工程

cd $GOPATH/src
mkdir demo
cd demo
govendor init

三、安装依赖

govendor fetch github.com/go-sql-driver/mysql@=v1.4.1
govendor fetch github.com/gin-gonic/gin@=v1.3.0
govendor fetch github.com/gomodule/redigo/redis@=v1.7.0

四、开发

package main

import (
	"database/sql"
	"log"

	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

var Database *sql.DB

func main() {
	DatabaseInit()
	defer Database.Close()
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	r.GET("/", IndexAction)
	r.GET("/user/:name", UserAction)
	r.Run()
}

func DatabaseInit() {
	var err error
	Database, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/wordpress")
	if err != nil {
		log.Fatalln(err)
	}
	Database.SetMaxIdleConns(500)
	Database.SetMaxOpenConns(500)
	err = Database.Ping()
	if err != nil {
		log.Fatalln(err)
	}
}

func IndexAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "index"})
}

func UserAction(c *gin.Context) {
	var ID int
	err := Database.QueryRow("SELECT ID FROM wp_users WHERE user_login = ?", c.Param("name")).Scan(&ID)
	if err == nil {
		c.String(200, "Hello %d", ID)
	} else {
		c.String(200, "Hello nobody")
	}
}

五、gin-app

gin-app-0.1