Submitted by gouki on 2013, September 5, 12:08 AM
不多说了。其实这是一个复刻版,原来的PHP代码就在注释里面。在google play上面已经存了代码了。如果你觉得我这里的代码看起来不方便,可以移步play.golang.org。
XML/HTML代码
- package main
-
- import (
- "fmt"
- "io/ioutil"
- "net/http"
- "net/url"
- "strings"
- "unicode/utf8"
- )
-
- /**
- //https://github.com/phurix/pagerank/blob/master/pagerank2.php
- function GetPageRank($q,$host='toolbarqueries.google.com',$context=NULL) {
- $seed = "Mining PageRank is AGAINST GOOGLE'S TERMS OF SERVICE. Yes, I'm talking to you, scammer.";
- $result = 0x01020345;
- $len = strlen($q);
- for ($i=0; $i<$len; $i++) {
- $result ^= ord($seed{$i%strlen($seed)}) ^ ord($q{$i});
- $result = (($result >> 23) & 0x1ff) | $result << 9;
- }
- if (PHP_INT_MAX != 2147483647) { $result = -(~($result & 0xFFFFFFFF) + 1); }
- $ch=sprintf('8%x', $result);
- $url='http://%s/tbr?client=navclient-auto&ch=%s&features=Rank&q=info:%s';
- $url=sprintf($url,$host,$ch,$q);
- @$pr=file_get_contents($url,false,$context);
- return $pr?substr(strrchr($pr, ':'), 1):false;
- }
- */
-
- func main() {
- fmt.Println(getPageRank("http://neaststudio.com"))
- }
-
- func getPageRank(urlstring string) string {
- seed := []byte("Mining PageRank is AGAINST GOOGLE'S TERMS OF SERVICE. Yes, I'm talking to you, scammer.")
- seedlen := len(seed)
- result := 0x01020345
- q := []byte(urlstring)
- qlen := len(q)
- for i := 0; i < qlen; i++ {
- seedmod := i % seedlen
- seed_ascii, _ := utf8.DecodeLastRuneInString(string(seed[seedmod]))
- q_ascii, _ := utf8.DecodeLastRuneInString(string(q[i]))
- result ^= int(seed_ascii ^ q_ascii)
- result = ((result >> 23) & 0x1ff) | result<<9
- }
- result = -(^(result & 0xffffffff) + 1)
- ch := fmt.Sprintf("8%x", result)
- u, _ := url.Parse("http://toolbarqueries.google.com/tbr")
- uq := u.Query()
- uq.Set("client", "navclient-auto")
- uq.Set("ch", ch)
- uq.Set("features", "Rank")
- uq.Set("q", "info:"+string(q))
- u.RawQuery = uq.Encode()
- resp, err := http.Get(u.String())
- if nil != err {
- return err.Error()
- }
- defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
- if nil != err {
- return err.Error()
- }
- //pagerank只有一位,所以可以直接取最后一位。。。免去正则
- if len(body) <= 0 {
- return "error"
- }
- pagerankbody := strings.TrimSpace(string(body[:]))
- return pagerankbody[len(pagerankbody)-1:]
- }
play.golang的地址是:http://play.golang.org/p/uACC-1rdF3
不过,在网页上执行会报错的,说是没有权限。。本地测试成功
Tags: pagerank
Go | 评论:0
| 阅读:15536
Submitted by gouki on 2013, September 3, 11:13 PM
有人在stackoverflow上面提问:
http://stackoverflow.com/questions/17776584/webserver-for-go-golang-webservices-using-nginx-or-not
- I am writing some webservices returning JSON data, which have lots of users.
- Would you recommend to use NGINX as a webserver or it is good enough to use the standard http server of Go?
于是有人就回答了:
XML/HTML代码
- It depends.
-
- Out of the box, putting nginx in front as a reverse proxy is going to give you:
-
- Access logs
- Error logs
- Easy SSL termination
- SPDY support
- gzip support
- Easy ways to set HTTP headers for certain routes in a couple of lines
- Very fast static asset serving (if you're serving off S3/etc. though, this isn't that relevant)
- 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).
-
- 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代码
- The standard http server of Go is fine. If your application mostly/only are "dynamic" requests/responses, then it's really the best way.
-
- 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).
-
- 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 | 评论:0
| 阅读:20060
Submitted by gouki on 2013, September 2, 11:08 PM
获取公网IP的方法其实很简单,最简单的就是利用dnspod的服务,echo `nc ns1.dnspod.net 6666`,立刻就出来了。于是hugozhu的一段代码就是这样写的:
XML/HTML代码
- func GetLocalPublicIpUseDnspod() (string, error) {
- timeout := time.Nanosecond * 30
- conn, err := net.DialTimeout("tcp", "ns1.dnspod.net:6666", timeout*time.Second)
- defer func() {
- if x := recover(); x != nil {
- log.Println("Can't get public ip", x)
- }
- if conn != nil {
- conn.Close()
- }
- }()
- if err == nil {
- var bytes []byte
- deadline := time.Now().Add(timeout * time.Second)
- err = conn.SetDeadline(deadline)
- if err != nil {
- return "", err
- }
- bytes, err = ioutil.ReadAll(conn)
- if err == nil {
- return string(bytes), nil
- }
- }
- return "", err
- }
上面的原始代码在:http://hugozhu.myalert.info/2013/02/26/dynamic-dns-script.html,原文的代码中其实是不能运行的。因为:timeout是个未定义的变量。
OK,不说这个。我在现实中不能使用上面的代码,因为nc ns1.dnspod.net取出来的结果不正确。为什么?因为我用的是铁通,好象会经过一层代理。但是我访问ip138又是可以取到真实的公网IP,所以我使用了如下代码 :
XML/HTML代码
- func GetLocalPublicIp() (string, error) {
- // `nc ns1.dnspod.cn 6666`
- res, err := http.Get("http://iframe.ip138.com/ic.asp")
- if err != nil {
- return "", err
- }
- defer res.Body.Close()
- result, err := ioutil.ReadAll(res.Body)
- if err != nil {
- return "", err
- }
- reg := regexp.MustCompile(`\d+\.\d+\.\d+\.\d+`)
- return reg.FindString(string(result)), nil
- }
上面我用的正则十分简单。就这样写写算了。因为这个页面里就这么一个符合的地方。OK,现在就一切正常了
Go | 评论:0
| 阅读:18483
Submitted by gouki on 2013, August 28, 6:47 PM
用Go来处理GET实在是太简单了。。
GET
- u, _ := url.Parse(SMS_URL)
- q := u.Query()
- q.Set("username", SMS_USER)
- q.Set("password", SMS_PASS)
- q.Set("mobile", s.To)
- q.Set("message", s.Content)
- u.RawQuery = q.Encode()
- res,err:=http.GET(u.String());
POST分多种,一种是key/value,一种是纯body,还有。。能够上传文件的。这里先不谈上传文件(我还没有用到)
XML/HTML代码
- body := bytes.NewBuffer(msg)
- res, err := http.Post(http://api.xxx.com/, "application/x-www-form-urlencoded", body)
-
- v := make(url.Values)
- v.Set("email", "anything@stathat.com")
- v.Set("stat", "messages sent - female to male")
- v.Set("count", "1")
- res, err := http.PostForm("http://api.xxx.com/", values)
处理res也非常方便:
XML/HTML代码
- if err != nil {
- log.Fatal(err)
- return
- }
- result, err := ioutil.ReadAll(res.Body)
- res.Body.Close()
- if err != nil {
- log.Fatal(err)
- return
- }
- fmt.Printf("%s", result)
就是这样的方便
Go | 评论:0
| 阅读:20384
Submitted by gouki on 2013, August 28, 11:49 AM
不要以为扫雷 就是游戏扫雷,其实只不过是扫清程序中可能会遇到的坑。比如原作者写的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.//实现前导零出错:sn:="7DC3"+fmt.printf("%05d", uint16(rawdata[2])&0xFF+uint16(rawdata[1]))
-
- &:[fmt.Printf返回的是一个int和一个error,不能与string用+号一起操作]
-
- sn := fmt.Sprintf("%s%05d", "7DC3", uint16(rawdata[2])&0xFF+uint16(rawdata[1]))或fmt.Sprintf("7DC3%05d",uint16(rawdata[2])&0xFF+uint16(rawdata[1]))
-
- 2.//fmt.Sprint不能输出
-
- &:根据fmt包API描述,fmt.Sprint是返回字符串,与fmt.Print的标准输出不同.
-
- 3.//go run *.go,且*.go引用同一packge中其他文件的函数时,提示undefined "函数名"
-
- &:[go run 时,只会编译当前文件再运行,没有导入其他文件的自定义函数]要先go build 再运行./*
-
- 4.//func FormatInt(i int64, base int) string,base的意思
-
- &:base表示进制,如八进制(8),十进制(10)等
-
- 5.//在if..else中定义同一个变量出错
-
- &:在golang语法中必须在外面先定义好,再在if..else结构中使用.
-
- 6.//go build/install 出错
-
- &:执行命令时需两个条件GOPATH和当前目录下有*.go的文件
-
- 7.//panic template: unexpected EOF
-
- &:可能是{{}}标签没有闭合
-
- 8.//error信息中template(*Template).Execute
-
- &:检查顺序:先确认go代码正确,然后看调用的模板名称是否正确或已存在,最后检查模板中的golang标签是否正确(或关闭)
-
- 9.//http.Get("www.ip138.com") unsupported protocol scheme ""
-
- &:使用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中的结构一致)
Go | 评论:0
| 阅读:19477