手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表分类:Go

getPageRank for golang

 不多说了。其实这是一个复刻版,原来的PHP代码就在注释里面。在google play上面已经存了代码了。如果你觉得我这里的代码看起来不方便,可以移步play.golang.org。

XML/HTML代码
  1. package main  
  2.   
  3. import (  
  4.     "fmt"  
  5.     "io/ioutil"  
  6.     "net/http"  
  7.     "net/url"  
  8.     "strings"  
  9.     "unicode/utf8"  
  10. )  
  11.   
  12. /**  
  13. //https://github.com/phurix/pagerank/blob/master/pagerank2.php  
  14. function GetPageRank($q,$host='toolbarqueries.google.com',$context=NULL) {  
  15.     $seed = "Mining PageRank is AGAINST GOOGLE'S TERMS OF SERVICE. Yes, I'm talking to you, scammer.";  
  16.     $result = 0x01020345;  
  17.     $len = strlen($q);  
  18.     for ($i=0; $i<$len; $i++) {  
  19.         $result ^= ord($seed{$i%strlen($seed)}) ^ ord($q{$i});  
  20.         $result = (($result >> 23) & 0x1ff) | $result << 9;  
  21.     }  
  22.     if (PHP_INT_MAX != 2147483647) { $result = -(~($result & 0xFFFFFFFF) + 1); }  
  23.     $ch=sprintf('8%x', $result);  
  24.     $url='http://%s/tbr?client=navclient-auto&ch=%s&features=Rank&q=info:%s';  
  25.     $url=sprintf($url,$host,$ch,$q);  
  26.     @$pr=file_get_contents($url,false,$context);  
  27.     return $pr?substr(strrchr($pr, ':'), 1):false;  
  28. }  
  29. */  
  30.   
  31. func main() {  
  32.     fmt.Println(getPageRank("http://neaststudio.com"))  
  33. }  
  34.   
  35. func getPageRank(urlstring string) string {  
  36.     seed := []byte("Mining PageRank is AGAINST GOOGLE'S TERMS OF SERVICE. Yes, I'm talking to you, scammer.")  
  37.     seedlen :len(seed)  
  38.     result :0x01020345  
  39.     q := []byte(urlstring)  
  40.     qlen :len(q)  
  41.     for i :0; i < qlen; i++ {  
  42.         seedmod :i % seedlen  
  43.         seed_ascii, _ :utf8.DecodeLastRuneInString(string(seed[seedmod]))  
  44.         q_ascii, _ :utf8.DecodeLastRuneInString(string(q[i]))  
  45.         result ^= int(seed_ascii ^ q_ascii)  
  46.         result = ((result >> 23) & 0x1ff) | result<<9  
  47.     }  
  48.     result = -(^(result & 0xffffffff) + 1)  
  49.     ch :fmt.Sprintf("8%x", result)  
  50.     u, _ :url.Parse("http://toolbarqueries.google.com/tbr")  
  51.     uq :u.Query()  
  52.     uq.Set("client", "navclient-auto")  
  53.     uq.Set("ch", ch)  
  54.     uq.Set("features", "Rank")  
  55.     uq.Set("q", "info:"+string(q))  
  56.     u.RawQuery = uq.Encode()  
  57.     resp, err :http.Get(u.String())  
  58.     if nil != err {  
  59.         return err.Error()  
  60.     }  
  61.     defer resp.Body.Close()  
  62.     body, err :ioutil.ReadAll(resp.Body)  
  63.     if nil != err {  
  64.         return err.Error()  
  65.     }  
  66.     //pagerank只有一位,所以可以直接取最后一位。。。免去正则  
  67.     if len(body) <= 0 {  
  68.         return "error"  
  69.     }  
  70.     pagerankbody :strings.TrimSpace(string(body[:]))  
  71.     return pagerankbody[len(pagerankbody)-1:]  
  72. }  

play.golang的地址是:http://play.golang.org/p/uACC-1rdF3

不过,在网页上执行会报错的,说是没有权限。。本地测试成功

 

Tags: pagerank

using NGINX or not?

 有人在stackoverflow上面提问:

http://stackoverflow.com/questions/17776584/webserver-for-go-golang-webservices-using-nginx-or-not
  1. I am writing some webservices returning JSON data, which have lots of users.    
  2. Would you recommend to use NGINX as a webserver or it is good enough to use the standard http server of Go?  

于是有人就回答了:

XML/HTML代码
  1. It depends.  
  2.   
  3. Out of the box, putting nginx in front as a reverse proxy is going to give you:  
  4.   
  5. Access logs  
  6. Error logs  
  7. Easy SSL termination  
  8. SPDY support  
  9. gzip support  
  10. Easy ways to set HTTP headers for certain routes in a couple of lines  
  11. Very fast static asset serving (if you're serving off S3/etc. though, this isn't that relevant)  
  12. The Go HTTP server is very good, but you will need to reinvent the wheel to do some of these things (which is fine: it's not meant to be everything to everyone).  
  13.   
  14. I've always found it easier to put nginx in front—which is what it is good at—and let it do the "web server" stuff. My Go application does the application stuff, and only the bare minimum of headers/etc. that it needs to. Don't look at putting nginx in front as a "bad" thing.  

还有人回答:

XML/HTML代码
  1. The standard http server of Go is fine. If your application mostly/only are "dynamic" requests/responses, then it's really the best way.  
  2.   
  3. You could use nginx to serve static assets, but most likely the standard Go one is fine for that, too. If you need higher performance you should just use a CDN or cache as much as you can with Varnish (for example).  
  4.   
  5. If you need to serve different applications off the same IP address, nginx is a fine choice for a proxy to distribute requests between the different applications; though I'd more often get Varnish or HAProxy out of the toolbox for that sort of thing.  

这回你觉得呢?你还会用nginx吗?还是只用go做http server/???

Tags: nginx, go

go获取当前的公网IP

 获取公网IP的方法其实很简单,最简单的就是利用dnspod的服务,echo `nc ns1.dnspod.net 6666`,立刻就出来了。于是hugozhu的一段代码就是这样写的:

XML/HTML代码
  1. func GetLocalPublicIpUseDnspod() (string, error) {  
  2.     timeout :time.Nanosecond * 30  
  3.     conn, err :net.DialTimeout("tcp", "ns1.dnspod.net:6666", timeout*time.Second)  
  4.     defer func() {  
  5.         if x :recover(); x != nil {  
  6.             log.Println("Can't get public ip", x)  
  7.         }  
  8.         if conn != nil {  
  9.             conn.Close()  
  10.         }  
  11.     }()  
  12.     if err == nil {  
  13.         var bytes []byte  
  14.         deadline :time.Now().Add(timeout * time.Second)  
  15.         err = conn.SetDeadline(deadline)  
  16.         if err != nil {  
  17.             return "", err  
  18.         }  
  19.         bytes, err = ioutil.ReadAll(conn)  
  20.         if err == nil {  
  21.             return string(bytes), nil  
  22.         }  
  23.     }  
  24.     return "", err  
  25. }  

上面的原始代码在:http://hugozhu.myalert.info/2013/02/26/dynamic-dns-script.html,原文的代码中其实是不能运行的。因为:timeout是个未定义的变量。

OK,不说这个。我在现实中不能使用上面的代码,因为nc ns1.dnspod.net取出来的结果不正确。为什么?因为我用的是铁通,好象会经过一层代理。但是我访问ip138又是可以取到真实的公网IP,所以我使用了如下代码 :

XML/HTML代码
  1. func GetLocalPublicIp() (string, error) {  
  2.     // `nc ns1.dnspod.cn 6666`  
  3.     res, err :http.Get("http://iframe.ip138.com/ic.asp")  
  4.     if err != nil {  
  5.         return "", err  
  6.     }  
  7.     defer res.Body.Close()  
  8.     result, err :ioutil.ReadAll(res.Body)  
  9.     if err != nil {  
  10.         return "", err  
  11.     }  
  12.     reg :regexp.MustCompile(`\d+\.\d+\.\d+\.\d+`)  
  13.     return reg.FindString(string(result)), nil  
  14. }  

上面我用的正则十分简单。就这样写写算了。因为这个页面里就这么一个符合的地方。OK,现在就一切正常了

go 进行简单的POST和GET

用Go来处理GET实在是太简单了。。

GET
  1. u, _ :url.Parse(SMS_URL)  
  2. :u.Query()  
  3. q.Set("username", SMS_USER)  
  4. q.Set("password", SMS_PASS)  
  5. q.Set("mobile", s.To)  
  6. q.Set("message", s.Content)  
  7. u.RawQuery = q.Encode()  
  8. res,err:=http.GET(u.String());  
POST分多种,一种是key/value,一种是纯body,还有。。能够上传文件的。这里先不谈上传文件(我还没有用到)
XML/HTML代码
  1.     body :bytes.NewBuffer(msg)  
  2.     res, err :http.Post(http://api.xxx.com/, "application/x-www-form-urlencoded", body)  
  3.   
  4. :make(url.Values)  
  5.         v.Set("email", "anything@stathat.com")  
  6.         v.Set("stat", "messages sent - female to male")  
  7.         v.Set("count", "1")  
  8.         res, err :http.PostForm("http://api.xxx.com/", values)  
处理res也非常方便:
XML/HTML代码
  1. if err != nil {  
  2.     log.Fatal(err)  
  3.     return  
  4. }  
  5. result, err :ioutil.ReadAll(res.Body)  
  6. res.Body.Close()  
  7. if err != nil {  
  8.     log.Fatal(err)  
  9.     return  
  10. }  
  11. fmt.Printf("%s", result)  
就是这样的方便
 
 
 
 
 

转:go语言扫雷

 不要以为扫雷 就是游戏扫雷,其实只不过是扫清程序中可能会遇到的坑。比如原作者写的if else中不能重复定义变量就是一个坑 。我原来想,我要定义一个变量,但他可能会变,特别是[]byte,长度只能用常量。这可怎么办,于是我想直接定义在if else中吧。if a { var a1 [128]byte} elseif b { var a1[256]byte},结果嘛,当然是报错的。。后来才发现这是个坑。当然后面我也解决了这个问题了。。。换个角度make一下。。make的时候就可以用变量了。

以下内容来自:http://my.oschina.net/meilihao/blog/123698

XML/HTML代码
  1. 1.//实现前导零出错:sn:="7DC3"+fmt.printf("%05d",  uint16(rawdata[2])&0xFF+uint16(rawdata[1]))  
  2.   
  3. &:[fmt.Printf返回的是一个int和一个error,不能与string用+号一起操作]  
  4.   
  5. sn :fmt.Sprintf("%s%05d", "7DC3", uint16(rawdata[2])&0xFF+uint16(rawdata[1]))或fmt.Sprintf("7DC3%05d",uint16(rawdata[2])&0xFF+uint16(rawdata[1]))  
  6.   
  7. 2.//fmt.Sprint不能输出  
  8.   
  9. &:根据fmt包API描述,fmt.Sprint是返回字符串,与fmt.Print的标准输出不同.  
  10.   
  11. 3.//go run *.go,且*.go引用同一packge中其他文件的函数时,提示undefined "函数名"  
  12.   
  13. &:[go run 时,只会编译当前文件再运行,没有导入其他文件的自定义函数]要先go build 再运行./*  
  14.   
  15. 4.//func FormatInt(i int64, base int) string,base的意思  
  16.   
  17. &:base表示进制,如八进制(8),十进制(10)等  
  18.   
  19. 5.//在if..else中定义同一个变量出错  
  20.   
  21. &:在golang语法中必须在外面先定义好,再在if..else结构中使用.  
  22.   
  23. 6.//go build/install 出错  
  24.   
  25. &:执行命令时需两个条件GOPATH和当前目录下有*.go的文件  
  26.   
  27. 7.//panic template: unexpected EOF  
  28.   
  29. &:可能是{{}}标签没有闭合  
  30.   
  31. 8.//error信息中template(*Template).Execute  
  32.   
  33. &:检查顺序:先确认go代码正确,然后看调用的模板名称是否正确或已存在,最后检查模板中的golang标签是否正确(或关闭)  
  34.   
  35. 9.//http.Get("www.ip138.com") unsupported protocol scheme ""  
  36.   
  37. &:使用http.Get时必须写明使用的协议,应使用http.Get("http://www.ip138.com")  
我另外遇到一个问题就是我定义了一下struct,然后我在init前,就

var a struct,但我在使用a.X = 1的时候就报错了。理由是我的a.X没有初始化。起初没看代码说明,后来仔细看了才发现。。。不得已,在var a struct下面加了一行var a.X int。(当然,这得和 sturct中的结构一致)

Records:3812345678