GolangNote

Golang笔记

Goji + mgo 示例

Permalink

Goji + mgo 示例

Go: goji+mgo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
 
import (
    "encoding/json"
    "flag"
    "log"
    "net/http"
 
    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)
 
type ErrorRes struct {
    Status  int    `json:"status-code"`
    Message string `json:"message"`
}
 
type Log struct {
    ID          bson.ObjectId `bson:"_id"`
    Account     string        `bson:"account"`
    IsSucceeded bool          `bson:"isSucceeded"`
    Site        string        `bson:"site"`
    Date        string        `bson:"date"`
    Message     []string      `bson:"message"`
}
 
func findAll() (r []Log) {
    session, err := mgo.Dial("mongodb://localhost")
    if err != nil {
        panic(err)
    }
    defer session.Close()
 
    session.SetMode(mgo.Monotonic, true)
    con := session.DB("db-name").C("log")
 
    err = con.Find(bson.M{}).All(&r)
    if err != nil {
        log.Fatal(err)
    }
    return r
}
 
func getLog(c web.C, w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    encoder := json.NewEncoder(w)
 
    if c.URLParams["APPID"] != "[Your APP ID]" {
        encoder.Encode(&ErrorRes{401, "Incorrect App ID"})
        return
    }
 
    result := findAll()
    encoder.Encode(result)
}
 
func main() {
    flag.Set("bind", ":8888")
    goji.Get("/log/:APPID", getLog)
    goji.Get("/logs/:APPID", http.RedirectHandler("/log/:APPID", 301))
    goji.Serve()
}

本文网址: https://golangnote.com/topic/114.html 转摘请注明来源

Related articles

bolt 使用示例

bolt 是一款高性能的key value 数据库,下面是它的使用示例:...

golang web 框架 goji 介绍

goji 是个后起的golang web框架,避免其它golang web 框架走过的坑,在性能、简单性方面做得很好。...

关掉goji 的log 输出

goji 默认对每个请求都输出请求时间,在项目刚起步时可以作为性能参考,但在实际生产环境里,可以关掉log...

Write a Comment to "Goji + mgo 示例"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms