Skip to content

Commit

Permalink
短链接框架
Browse files Browse the repository at this point in the history
  • Loading branch information
samael65535 committed Jun 4, 2017
1 parent ae2f6f2 commit 58d861d
Show file tree
Hide file tree
Showing 11 changed files with 494 additions and 6 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
*.elc
Processing/**/output/
Processing/libraries
Golang/tinyurl/bin
Golang/tinyurl/pkg
Golang/**/bin
Golang/**/pkg
45 changes: 45 additions & 0 deletions Golang/ShortenURL/src/controllers/index.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package controllers

import (
"fmt"
"github.com/hoisie/web"
"html/template"
"log"
"models"
"net/http"
)

type indexController struct {
template *template.Template
}

func (this *indexController) get(ctx *web.Context, val string) {
if val == "" {
r := result{"", ""}
// 查询有没有命中
fmt.Println(this.template.Execute(ctx.ResponseWriter, r))
} else {
if url, ok := models.Get(val); ok {
log.Print(url)
ctx.Redirect(http.StatusFound, url)
} else {
ctx.NotFound("url")
}
}

}

type result struct {
Tiny string
Origin string
}

func (this *indexController) post(ctx *web.Context, val string) {
originUrl, ok := ctx.Params["origin"]
if !ok {
ctx.NotFound("hello")
}
tinyUrl := models.Add(originUrl)
r := result{tinyUrl, originUrl}
fmt.Println(this.template.Execute(ctx.ResponseWriter, r))
}
24 changes: 24 additions & 0 deletions Golang/ShortenURL/src/controllers/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package controllers

import (
"github.com/hoisie/web"
"html/template"
)

// 注册服务器
func Register(t *template.Template) {
server := web.NewServer()
server.Config.StaticDir = "public/"

ic := new(indexController)
ic.template = t.Lookup("index.html")
server.Get("/(.*)", ic.get)
server.Post("/(.*)", ic.post)
server.Run("localhost:9999")

}

// 静态资源
func serveResource() {

}
75 changes: 75 additions & 0 deletions Golang/ShortenURL/src/helper/num62/num62.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package num62

const BASE = 62

var ALPHABET [62]byte

func init() {
var b byte
for r := 0; r < 62; r++ {
if r >= 0 && r <= 9 {
b = byte(r + 48)
} else if r >= 10 && r < 36 {
b = byte(r + 65 - 10)
} else {
b = byte(r + 97 - 36)
}
ALPHABET[r] = b
}
}
func Encode(num uint) string {

/*
BenchmarkEncode-8 10000000 176 ns/op
res := ""
for {
if num < BASE {
res = string(ALPHABET[num]) + res
break
} else {
res = string(ALPHABET[num%BASE]) + res
num = num / BASE
}
}
*/
res := []byte{}
for {
r := num % BASE
res = append(res, ALPHABET[r])
// s := []int{1}
// s, s[0] = append(s[0:1], s[0:]...), 3
// 使用unshift
// BenchmarkEncode-8 20000000 72.9 ns/op
// 使用先append 后reverse
// BenchmarkEncode-8 20000000 66.6 ns/op
num = num / BASE
if num == 0 {
break
}
}

return string(reverse(res))
}

func reverse(b []byte) []byte {
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return b
}
func Decode(n62 string) uint {
res := uint(0)
s := uint(1)
for i := len(n62) - 1; i >= 0; i-- {
c := n62[i]
if c >= 'A' && c <= 'Z' {
res += (uint(c) - 65 + 10) * s
} else if c >= '0' && c <= '9' {
res += (uint(c) - 48) * s
} else if c >= 'a' && c <= 'z' {
res += (uint(c) - 97 + 36) * s
}
s *= BASE
}
return res
}
43 changes: 43 additions & 0 deletions Golang/ShortenURL/src/helper/num62/num62_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package num62

import (
"testing"
)

func handleEncode(t *testing.T, arg uint, e string) {
if Encode(arg) != e {
t.Errorf("Encode: the result should be %s but %s\n", e, Encode(arg))
}
}

func TestEncode(t *testing.T) {
handleEncode(t, 0, "0")
handleEncode(t, 1, "1")
handleEncode(t, 61, "z")
handleEncode(t, 124, "20")
}

func handleDecode(t *testing.T, arg string, e uint) {
if Decode(arg) != e {
t.Errorf("Decode %s : the result should be %d but %d\n", arg, e, Decode(arg))
}
}

func TestDecode(t *testing.T) {
handleDecode(t, "10", 62)
handleDecode(t, "z", 61)
handleDecode(t, "11", 63)
handleDecode(t, "000z0", 62*61)
}

func BenchmarkEncode(b *testing.B) {
for i := 0; i < b.N; i++ {
Encode(uint(i))
}
}

func BenchmarkDecode(b *testing.B) {
for i := 0; i < b.N; i++ {
Decode("zzzzzzz")
}
}
34 changes: 34 additions & 0 deletions Golang/ShortenURL/src/main/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"controllers"

"html/template"
"os"
)

func main() {
templates := populateTemplates()
controllers.Register(templates)
}

func populateTemplates() *template.Template {
// 解析缓存templates
result := template.New("templates")
basePath := "templates"
templateFolder, _ := os.Open(basePath)
defer templateFolder.Close()

templatePathsRaw, _ := templateFolder.Readdir(-1)

templatePaths := new([]string)

for _, pathInfo := range templatePathsRaw {
if !pathInfo.IsDir() {
*templatePaths = append(*templatePaths, basePath+"/"+pathInfo.Name())
}
}
result.ParseFiles(*templatePaths...)

return result
}
50 changes: 50 additions & 0 deletions Golang/ShortenURL/src/models/database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package models

import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)

var session *mgo.Session
var collection *mgo.Collection

func InitDB() error {
var err error
session, err = mgo.Dial("127.0.0.1")
if err != nil {
return err
}

session.SetMode(mgo.Monotonic, true)
collection = session.DB("tinyurl").C("url")
return nil
}

func CloseDB() {
if session != nil {
session.Close()
}
}

func SaveDB(m *URLModel) error {
err := collection.Insert(m)
return err

}
func FindWithOrigin(origin string) (*URLModel, error) {
u := &URLModel{}
err := collection.Find(bson.M{"Origin": origin}).One(u)
if err != nil {
return nil, err
}
return u, nil
}

func FindWithShorten(shorten string) (*URLModel, error) {
u := &URLModel{}
err := collection.Find(bson.M{"shorten": shorten}).One(u)
if err != nil {
return nil, err
}
return u, nil
}
Loading

0 comments on commit 58d861d

Please sign in to comment.