Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a new feature #3

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added _examples/1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added _examples/2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added _examples/3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions _examples/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package main

import (
"fmt"
"os"

"github.com/qAison/captcha"
)

func main() {
id := captcha.New()
fileName := id + ".png"
if oFile, err := os.Create(fileName); err != nil {
fmt.Printf("create file error:%s\n", err.Error())
} else {
defer oFile.Close()

if err = captcha.WriteImage(oFile, id); err != nil {
fmt.Printf("image write error:%s\n", err.Error())
} else {
fmt.Printf("create image success:%s\n", fileName)
}
}
}
134 changes: 134 additions & 0 deletions _examples/web/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package main

import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"path"
"strings"
"text/template"
"time"

"github.com/qAison/captcha"
)

var (
formTemplate = template.Must(template.New("example").Parse(formTemplateSrc))
)

const (
CST_ID_LEN = 32
CST_VAL_LEN = 4
)

func init() {
captcha.SetGenIdLen(CST_ID_LEN)
}

//-----------------------------------------------------------------------------------------------------------//

type captchaHandler struct {
length int
}

func Server(length int) http.Handler {
return &captchaHandler{
length: length,
}
}

func (self *captchaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, id := path.Split(r.URL.Path)
if id = strings.TrimSpace(id); len(id) != CST_ID_LEN {
http.NotFound(w, r)
return
}

if r.FormValue("reload") != "" {
captcha.ReloadGen(id, self.length)
}

w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
w.Header().Set("Content-Type", "image/png")

buf := new(bytes.Buffer)
if err := captcha.WriteImage(buf, id); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
http.ServeContent(w, r, id+".png", time.Now(), bytes.NewReader(buf.Bytes()))
}
}

//-----------------------------------------------------------------------------------------------------------//

func showFormHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
d := struct {
CaptchaId string
}{
captcha.NewLen(CST_VAL_LEN),
}
if err := formTemplate.Execute(w, &d); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

func processFormHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if !captcha.Verify(r.FormValue("captchaId"), r.FormValue("captchaValue")) {
io.WriteString(w, "xxx 验证码错误 xxx")
} else {
io.WriteString(w, "~~~ 验证码正确 ~~~")
}
io.WriteString(w, "<br><br><a href='/'>继续再尝试</a>")
}

// ulimit -HSn 65535
func main() {
http.HandleFunc("/", showFormHandler)
http.HandleFunc("/process", processFormHandler)
http.Handle("/captcha/", Server(CST_VAL_LEN))
addr := "0.0.0.0:8666"
fmt.Println("Server is at " + addr)
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatal(err)
}
}

const formTemplateSrc = `<!doctype html>
<head><title>验证码示例</title></head>
<body>
<script>
function setSrcQuery(e, q) {
var src = e.src;
var p = src.indexOf('?');
if (p >= 0) {
src = src.substr(0, p);
}
e.src = src + "?" + q
}

function reload() {
setSrcQuery(document.getElementById('image'), "reload=" + (new Date()).getTime());
return false;
}
</script>

<form action="/process" method=post>
<p>请输入下面的验证码:</p>
<p><img id=image src="/captcha/{{.CaptchaId}}" alt="验证码图片"></p>

<a href="#" onclick="reload()">刷新</a>

<input type=hidden name=captchaId value="{{.CaptchaId}}"><br>
<input name=captchaValue>
<input type=submit value=提交>
</form>
`
122 changes: 122 additions & 0 deletions cache/memory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package cache

import (
"container/list"
"sync"
"time"
)

type Cache interface {
Set(key, value interface{})
Get(key interface{}) interface{}
Delete(key interface{})
UpdateTime(key interface{})
Len() int
Clear()
}

//-----------------------------------------------------------------------------------------------------------//

type memStore struct {
key interface{}
value interface{}
createTime time.Time
}

type memCache struct {
lock sync.RWMutex
values map[interface{}]*list.Element
list *list.List
ageTime int64
}

func New(ageTime int64) Cache {
mc := &memCache{
values: make(map[interface{}]*list.Element),
list: list.New(),
}
if ageTime <= 0 {
ageTime = 60
}
mc.ageTime = ageTime
go mc.gc()
return mc
}

func (self *memCache) Len() int {
self.lock.RLock()
defer self.lock.RUnlock()
return len(self.values)
}

func (self *memCache) Set(key, value interface{}) {
self.Delete(key)

self.lock.Lock()
defer self.lock.Unlock()

val := memStore{
key: key,
value: value,
createTime: time.Now(),
}
self.values[key] = self.list.PushFront(&val)
}

func (self *memCache) Get(key interface{}) interface{} {
self.lock.RLock()
defer self.lock.RUnlock()
if el, ok := self.values[key]; ok {
return el.Value.(*memStore).value
} else {
return nil
}
}

func (self *memCache) UpdateTime(key interface{}) {
self.lock.Lock()
defer self.lock.Unlock()
if el, ok := self.values[key]; ok {
el.Value.(*memStore).createTime = time.Now()
self.list.MoveToFront(el)
}
}

func (self *memCache) Delete(key interface{}) {
self.lock.Lock()
defer self.lock.Unlock()
if el, ok := self.values[key]; ok {
delete(self.values, key)
self.list.Remove(el)
}
}

func (self *memCache) Clear() {
self.lock.Lock()
defer self.lock.Unlock()
self.values = make(map[interface{}]*list.Element)
self.list = list.New()
}

func (self *memCache) gc() {
var interval int64
for {
self.lock.RLock()

if el := self.list.Back(); el != nil {
interval = el.Value.(*memStore).createTime.Unix() + self.ageTime - time.Now().Unix()
if interval <= 0 {
self.lock.RUnlock()
self.lock.Lock()
delete(self.values, el.Value.(*memStore).key)
self.list.Remove(el)
self.lock.Unlock()
continue
}
} else {
interval = 1
}
self.lock.RUnlock()
time.Sleep(time.Second * time.Duration(interval))
}
}
Loading