Mon, 9 Mar 2015 12:32 am
Single file #webkoe server written in #go :)
package main import ( "github.com/go-martini/martini" "github.com/martini-contrib/render" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "net" "net/http" "fmt" "time" "crypto/rand" "strings" "regexp" ) // local var mongoConfig = "127.0.0.1:27017" var blogCollection = "webkoe_blog" var hostHome = "localhost:8080" var hostCatatan = "catatan" // webkoe // var mongoConfig = "mongodb://usermongo:passmongo@localhost:portmongo/dbmongo" // var blogCollection = "blog" // var hostHome = "webkoe.net:8080" // var hostCatatan = "catatan.webkoe.net" type Blog struct { Id string Things string Date string Ip string Agent string Tag []string } func GetIP(r *http.Request) string { if ipProxy := r.Header.Get("X-FORWARDED-FOR"); len(ipProxy) > 0 { return ipProxy } ip, _, _ := net.SplitHostPort(r.RemoteAddr) return ip } func randStr(strSize int, randType string) string { var dictionary string if randType == "alphanum" { dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" } if randType == "alpha" { dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" } if randType == "number" { dictionary = "0123456789" } var bytes = make([]byte, strSize) rand.Read(bytes) for k, v := range bytes { bytes[k] = dictionary[v%byte(len(dictionary))] } return string(bytes) } func main() { // MARTINI m := martini.Classic() m.Use(render.Renderer(render.Options{ Layout: "layout", })) // MONGODB session, err := mgo.Dial(mongoConfig) if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) webkoe_blog := session.DB("admin").C(blogCollection) // ROUTER m.Get("/", func(r render.Render, req *http.Request) { if req.Host == hostHome { r.HTML(200, "home", req.Host) }else if req.Host == hostCatatan { r.HTML(200, "home-catatan", req.Host) } }) m.Get("/blog", func(r render.Render) { var results []Blog err = webkoe_blog.Find(bson.M{}).Sort("-date").Limit(100).All(&results) if err != nil { panic(err) } // fmt.Println(results) r.HTML(200, "blog", results) }) m.Post("/blog", func(req *http.Request, r render.Render){ things := req.FormValue("things") + " " // tag regex, err := regexp.Compile("#([a-z])+ ") remove, err := regexp.Compile("(#| )") tags := regex.FindAllString(things, -1) // fmt.Println(tags) // modify semua listA var modTags []string for _, value := range tags { final := remove.ReplaceAllString(value, "") modTags = append(modTags, final) } // fmt.Println(modTags) waktu := strings.Split(fmt.Sprint(time.Now()), ".")[0] blog_id := randStr(7, "alphanum") ip := GetIP(req) agent := fmt.Sprint(req.Header["User-Agent"]) jsonBlog := &Blog{Id: blog_id, Things: things, Date: waktu, Ip: ip, Agent: agent, Tag: modTags} err = webkoe_blog.Insert(jsonBlog) if err != nil { panic(err) } // fmt.Println(agent) r.Redirect("/blog") }) m.Get("/blog/write", func(r render.Render) { r.HTML(200, "blog-form", nil) }) m.RunOnAddr(":8080") }
Additional Info: