Sat, 21 Mar 2015 6:19 am
server-gorilla.go
package main

    import (
        "fmt"
        "github.com/gorilla/mux"
        "github.com/gorilla/sessions"
        "github.com/fzzy/radix/redis"
        "net"
        "net/http"
        "html/template"
        "gopkg.in/mgo.v2"         
        "gopkg.in/mgo.v2/bson"
        "regexp"
        "strings"
        "crypto/rand"
        "time"
        // "reflect"
    )
    
    var (
        // MongoDB
        mongoConfig       = "mongodb://***usermongo***:***passmongo***@localhost:***portmongo***/***dbmongo***"
        MongoSession, err = mgo.Dial(mongoConfig)
        MDB               = MongoSession.DB("admin")
        MCol              = MDB.C("blog")

        // Session
        store             = sessions.NewCookieStore([]byte("something-very-secret"))

        // Tag Factory
        tagPattern        = "#([a-z]|[A-Z])+"
    )

    type Blog struct {
      Id string
      Things string
      Date string
      Ip string
      Agent string
      Tag []string
    }

    // type tagView struct {
    //   tagName string
    //   tagList []main.Blog
    // }

    func WkHomeHandler(w http.ResponseWriter, r *http.Request) {
        err := template.Must(template.ParseFiles("templates/webkoe-home.html")).Execute(w, nil) 
        if err != nil { 
           http.Error(w, err.Error(), http.StatusInternalServerError) 
        } 
    }

    func WkTagViewHandler(w http.ResponseWriter, r *http.Request) {
        
        tagName := mux.Vars(r)["tag"]
        
        funcMap := template.FuncMap{
            "safehtml": func(text string) template.HTML { 

                text = text + " "
                text = strings.Replace(text, "<", "<", -1)   
                text = strings.Replace(text, ">", ">", -1) 
                  
                text = strings.Replace(text, "
", "
", -1) 
                text = strings.Replace(text, "
", "
", -1) regexPagar, _ := regexp.Compile(tagPattern) tags := regexPagar.FindAllString(text, -1) for _ , value := range tags { tagAscii := strings.Replace(value, "#", "#", 1) tagOnly := strings.Replace(value, "#", "", 1) text = strings.Replace(text, value, "" + tagAscii + "", 1) } return template.HTML(text) }, } templates := template.Must(template.New("").Funcs(funcMap).ParseFiles("templates/webkoe-base.html", "templates/webkoe-tagview.html")) var results []Blog err = MCol.Find(bson.M{"tag": tagName}).Sort("-date").Limit(1000000000000).All(&results) if err != nil { panic(err) } err := templates.ExecuteTemplate(w, "base", results) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkCreateHandler(w http.ResponseWriter, r *http.Request) { blog_id := randStr(7, "alphanum") session, _ := store.Get(r, "session-name") session.Values["blog_id"] = blog_id session.Save(r, w) templates := template.Must(template.New("").ParseFiles("templates/webkoe-base.html", "templates/webkoe-create.html")) err := templates.ExecuteTemplate(w, "base", blog_id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkPostCreateHandler(w http.ResponseWriter, r *http.Request) { things := r.FormValue("things") thingsWithSpace := things + " " captcha := r.FormValue("captcha") session,_ := store.Get(r, "session-name") blog_id := fmt.Sprintf("%s", session.Values["blog_id"]) if things != "" { if captcha == blog_id { // Factory cariTag,_ := regexp.Compile(tagPattern) tagFound := cariTag.FindAllString(thingsWithSpace, -1) var tempTags []string for _, value := range tagFound { cleanRegex,_ := regexp.Compile("(#| )") cleanTag := cleanRegex.ReplaceAllString(value, "") tempTags = append(tempTags, cleanTag) } waktu := strings.Split(fmt.Sprint(time.Now()), ".")[0] ip := GetIP(r) agent := fmt.Sprint(r.Header["User-Agent"]) jsonBlog := &Blog{Id: blog_id, Things: things, Date: waktu, Ip: ip, Agent: agent, Tag: tempTags} err = MCol.Insert(jsonBlog) fmt.Println("Welcome, " + things + " " + thingsWithSpace) http.Redirect(w, r, "/#thanks", 301) }else{ fmt.Println("Robot ?") http.Redirect(w, r, "/#you_r_a_bots", 301) } }else{ http.Redirect(w, r, "/#empty", 301) } // fmt.Println("Someone POST " + things + " blog_id " + blog_id) // fmt.Println(blog_id) /* templates := template.Must(template.New("").ParseFiles("templates/webkoe-base.html", "templates/webkoe-create.html")) err := templates.ExecuteTemplate(w, "base", nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } */ } func WkListHandler(w http.ResponseWriter, r *http.Request) { funcMap := template.FuncMap{ "safehtml": func(text string) template.HTML { text = text + " " text = strings.Replace(text, "<", "<", -1) text = strings.Replace(text, ">", ">", -1) text = strings.Replace(text, "
", "
", -1) 
                text = strings.Replace(text, "
", "
", -1) regexPagar, _ := regexp.Compile(tagPattern) tags := regexPagar.FindAllString(text, -1) for _ , value := range tags { tagAscii := strings.Replace(value, "#", "#", 1) tagOnly := strings.Replace(value, "#", "", 1) text = strings.Replace(text, value, "" + tagAscii + "", 1) } return template.HTML(text) }, } templates := template.Must(template.New("").Funcs(funcMap).ParseFiles("templates/webkoe-base.html", "templates/webkoe-list.html")) var results []Blog err = MCol.Find(bson.M{}).Sort("-date").Limit(1000000000000).All(&results) if err != nil { panic(err) } // var finalResult []tagView // fmt.Println(reflect.TypeOf(results)) err := templates.ExecuteTemplate(w, "base", results) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func CatatanHomeHandler(w http.ResponseWriter, r *http.Request) { var results []Blog err = MCol.Find(bson.M{}).Sort("-date").Limit(100).All(&results) if err != nil { panic(err) } err := template.Must(template.ParseFiles("templates/gorilla-catatanhome.html")).Execute(w, results) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func HomeWKSHandler(w http.ResponseWriter, r *http.Request) { err := template.Must(template.ParseFiles("templates/gorilla-home_wks.html")).Execute(w, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkBlogHandler(w http.ResponseWriter, r *http.Request) { page := mux.Vars(r)["page"] err := template.Must(template.ParseFiles("templates/gorilla-blog.html")).Execute(w, map[string]string{"halaman": page}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkRedisHandler(w http.ResponseWriter, r *http.Request) { // redis redisClient, _ := redis.Dial("tcp", "localhost:6379") news, _ := redisClient.Cmd("zrevrangebyscore", "news:republika:posttime", "+inf", "-inf", "limit", "0", "3").List() var bundleNews []string for _, elemStr := range news { bundleNews = append(bundleNews, elemStr) fmt.Println(bundleNews) } // render err := template.Must(template.ParseFiles("templates/gorilla-redis.html")).Execute(w, bundleNews) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkTestPassVarHandler(w http.ResponseWriter, r *http.Request) { err := template.Must(template.ParseFiles("templates/gorilla-blog.html")).Execute(w, map[string]string{"halaman": "2"}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } 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 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 main() { // MUX ROUTER mx := mux.NewRouter() // WEBKOE.NET // *** home *** mx.HandleFunc("/", WkListHandler).Host("webkoe.net") // *** tag *** mx.HandleFunc("/tag/{tag}", WkTagViewHandler).Host("webkoe.net").Methods("GET") // *** create *** mx.HandleFunc("/create", WkCreateHandler).Host("webkoe.net").Methods("GET") mx.HandleFunc("/create", WkPostCreateHandler).Host("webkoe.net").Methods("POST") // *** misc *** mx.HandleFunc("/test/pass_var", WkTestPassVarHandler).Host("webkoe.net") mx.HandleFunc("/redis", WkRedisHandler).Host("webkoe.net") mx.HandleFunc("/page/{page}", WkBlogHandler).Host("webkoe.net") mx.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/"))).Host("webkoe.net") // CATATAN.WEBKOE.NET mx.HandleFunc("/", CatatanHomeHandler).Host("catatan.webkoe.net") // WEBKANSAJA.COM mx.HandleFunc("/", HomeWKSHandler).Host("webkansaja.com") http.ListenAndServe(":80", mx) }
#script #go #webkoe
183
Additional Info: