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

Write a Comment to "Goji + mgo 示例"

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