go 语言开发2 简易数据库和web代码示例

 

  • 数据库开发示例
package dao

import (
    "github.com/go-xorm/xorm"
    "fmt"
)

type UserInfo struct {
    UserId     string `xorm:"userId varchar(60)"`
    Username string `xorm:"username varchar(60)"`
}

func GetWeixinConfig() {
    var engine *xorm.Engine
    var err error
    engine, err = xorm.NewEngine("mysql", "username:password@tcp(host:port)/user_db")
    if err != nil {
        fmt.Println(err)
    }
    err1 := engine.Ping()
    if err1 != nil {
        fmt.Println(err1)
    }
    engine.ShowSQL(true)
    var users []UserInfo

    err2 := engine.Table("user_db").Select("userId, username").
        Find(&users)
    if err2 != nil {
        fmt.Println(err)
    }
    fmt.Println(len(users))
}

 

  • go web 开发示例
package main

import (
    "github.com/gin-gonic/gin"
    "awesome-go/src/dao"
    "os"
    "io"
)

func main() {
    //输出日志到文件
    gin.DisableConsoleColor()
    logFile, _ := os.Create("log")
    gin.DefaultWriter = io.MultiWriter(logFile)

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

 

  • gin web开发示例
package main

import (
    "github.com/gin-gonic/gin"
    "awesome-go/src/dao"
    "os"
    "io"
)

func main() {
    //输出日志到文件
    gin.DisableConsoleColor()
    logFile, _ := os.Create("log")
    gin.DefaultWriter = io.MultiWriter(logFile)

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

 

posted @ 2018-05-29 19:56  风小雅  阅读(950)  评论(0编辑  收藏  举报