golang解析html文件
由于项目中需要用到json,使用的是https://github.com/bitly/go-simplejson.git
下载到配置的&gopath路径的src下面
连接的地址是:
"http://lengxiaohua.com/lengxiaohuaapi/joke?action=getJokes&interval=weekly&sort=popular&type=text%7Cimage&start=0&limit=20"
步骤很简单
3.解析json,打印到控制台
代码很简单如下,直接运行就可以
</pre><pre name="code" class="cpp">// TestGoCommand project main.go package main import ( "encoding/json" "fmt" "go-simplejson" // for json get //"gopkg.in/mgo.v2" //"gopkg.in/mgo.v2/bson" "io/IoUtil" "net/http" //"regexp" //"strconv" ) func Get(url string) (content string,statusCode int) { resp,err1 := http.Get(url) if err1 != nil { statusCode = -100 return } defer resp.Body.Close() data,err2 := IoUtil.ReadAll(resp.Body) if err2 != nil { statusCode = -200 return } js,err := simplejson.NewJson(data) if err != nil { panic(err.Error()) } weilist := []weidata{}[:] for _,v := range js.Get("jokes").MustArray() { prase(v) //append(weilist,prase(v)) //fmt.Println(i,v) } fmt.Print(weilist) statusCode = resp.StatusCode content = string(data) return } /**interface的强制类型转换**/ func prase(m1 interface{}) (wei weidata) { var dat map[string]interface{} dat = m1.(map[string]interface{}) wei = weidata{dat["uri"].(string),dat["user_name"].(string),dat["content"].(string),string(dat["Jokeid"].(json.Number))} fmt.Println("",wei) return } type weidata struct { url string title string content string key string } func main() { fmt.Println(`Get index ...`) _,statusCode := Get("http://lengxiaohua.com/lengxiaohuaapi/joke?action=getJokes&interval=weekly&sort=popular&type=text%7Cimage&start=0&limit=20") if statusCode != 200 { return } }运行结果: