Skip to content

Instantly share code, notes, and snippets.

@Ji-Yuhang
Created April 18, 2020 14:39
Show Gist options
  • Save Ji-Yuhang/37e270a535d89f7d5320c2e6443ce815 to your computer and use it in GitHub Desktop.
Save Ji-Yuhang/37e270a535d89f7d5320c2e6443ce815 to your computer and use it in GitHub Desktop.
go语言gin demo
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-pg/pg"
)
type Word struct {
Id int64
//Content string
Word string
//CreatedAt time.Time
//CreatedAt time.Time
//
}
type SimpleWord struct {
Id int64
WordId int64
Content string
//Word string
//CreatedAt time.Time
//CreatedAt time.Time
//
}
func main() {
db := pg.Connect(&pg.Options{
User: "postgres",
//Password: "postgres",
Password: "postgres",
Database: "iamyuhang_production",
//Database: "iamyuhang_development",
})
defer db.Close()
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.GET("/api/v1/words/search", func(c *gin.Context) {
word := c.Query("word")
var sw SimpleWord
_, err2 := db.QueryOne(&sw, `SELECT * FROM simple_words WHERE content = ?`, word)
fmt.Println(sw)
fmt.Println(err2)
var s = word + "%"
fmt.Println(fmt.Sprintf("'%s'", s))
if sw.WordId != 0 {
var sws []SimpleWord
_, err3 := db.Query(&sws, `SELECT * FROM simple_words WHERE content like ? limit 50`, fmt.Sprintf("'%s'", s))
fmt.Println(sws)
fmt.Println(err3)
c.JSON(200, gin.H{
"word": sw,
"words": sws,
"err": err2,
"er2": err3,
})
} else {
var w Word
_, err := db.QueryOne(&w, `SELECT * FROM words WHERE word = ?`, word)
fmt.Println(w)
fmt.Println(err)
var sws []SimpleWord
_, err3 := db.Query(&sws, `SELECT * FROM words WHERE word like ? limit 50`, fmt.Sprintf("'%s'", s))
fmt.Println(sws)
fmt.Println(err3)
//db.Prepare("select * from simple_words where content like ")
//stmt, err := db.Prepare(`SELECT $1::text, $2::text`)
//panicIf(err)
//
//var s1, s2 string
//_, err = stmt.QueryOne(pg.Scan(&s1,), "foo", "bar")
//panicIf(err)
//fmt.Println(s1, s2)
c.JSON(200, gin.H{
"word": w,
"words": sws,
"err": err2,
"er2": err3,
})
}
})
r.Run() // listen and serve on 0.0.0.0:8080
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment