golang – 从http请求返回json字符串的库/包

huangapple go评论91阅读模式
英文:

golang - library/package that returns json string from http request

问题

有没有返回http请求响应中接收到的json字符串的库/包。这很简单,所以我可以自己写,但是我更喜欢现有/经过测试的代码,而不是重新发明轮子。

目前,我有:

func getJsonStr(url string) ([]byte, error) {	
    resp, err := http.Get(url)
	if err != nil {
		return []byte{0}, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return []byte{0}, err
	}
	return body, nil
}

编辑:我正在寻找类似Node的'request'模块的东西,它让我可以一行代码完成,就像这样:jsonStr,err := getJsonStr(url)。

英文:

Is there any library/package that returns the json string received in response to an http request. It's pretty straightforward, so I can write my own, but would prefer existing/tested code over reinventing the wheel.

Currently, I have:

func getJsonStr(url string) ([]byte, error) {	
    resp, err := http.Get(url)
	if err != nil {
		return []byte{0}, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return []byte{0}, err
	}
	return body, nil
}

EDIT: I'm looking for something like Node's 'request' module, which lets me do it in one line, like so: jsonStr, err := getJsonStr(url).

答案1

得分: 10

由于您不想定义一个结构体,所以也可以将其解组为类型为map[string]interface{}{}的映射(但有点丑陋)。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {

    data := map[string]interface{}{}

    r, _ := http.Get("http://api.stackoverflow.com/1.1/tags?pagesize=100&page=1")
    defer r.Body.Close()

    body, _ := ioutil.ReadAll(r.Body)
    json.Unmarshal(body, &data)

    fmt.Println("Total:", data["total"], "page:", data["page"], "pagesize:", data["pagesize"])
    // Total: 34055 page: 1 pagesize: 100
}
英文:

Since you didn't want to define a struct, it's also possible (but a bit ugly) to unmarshal into a map of type map[string]interface{}{}

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {

	data := map[string]interface{}{}

	r, _ := http.Get("http://api.stackoverflow.com/1.1/tags?pagesize=100&page=1")
	defer r.Body.Close()

	body, _ := ioutil.ReadAll(r.Body)
	json.Unmarshal(body, &data)

	fmt.Println("Total:", data["total"], "page:", data["page"], "pagesize:", data["pagesize"])
	// Total: 34055 page: 1 pagesize: 100
}

答案2

得分: 7

使用现有的系统包没有问题,并且在Go语言中通过HTTP获取JSON数据非常简单。

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

func main() {
	var data struct {
		Items []struct {
			Name              string
			Count             int
			Is_required       bool
			Is_moderator_only bool
			Has_synonyms      bool
		}
	}

	r, _ := http.Get("https://api.stackexchange.com/2.2/tags?page=1&pagesize=100&order=desc&sort=popular&site=stackoverflow")
	defer r.Body.Close()

	dec := json.NewDecoder(r.Body)
	dec.Decode(&data)

	for _, item := range data.Items {
		fmt.Printf("%s = %d\n", item.Name, item.Count)
	}

}

输出结果 go run main.go

java = 781454
javascript = 769128
c# = 744294
php = 692360
android = 617892
jquery = 570461
python = 379608
html = 374617
c++ = 341533
ios = 300992
mysql = 296223
css = 276063
sql = 258178
asp.net = 244833
objective-c = 215095
.net = 202087
iphone = 199749
ruby-on-rails = 190497
c = 166226
ruby = 123840
sql-server = 119341
arrays = 116975
ajax = 109786
regex = 107215
xml = 106705
asp.net-mvc = 101921
json = 101545
wpf = 96016
linux = 92266
django = 88008
database = 86638
eclipse = 79952
vb.net = 78888
r = 78401
xcode = 76326
windows = 74359
angularjs = 73266
string = 71149
html5 = 68094
node.js = 66731
wordpress = 65125
multithreading = 64168
facebook = 62460
excel = 58402
spring = 57380
image = 56798
winforms = 55268
forms = 54263
ruby-on-rails-3 = 52611
osx = 51292
oracle = 50876
git = 50019
performance = 48867
swing = 48768
algorithm = 48258
apache = 47355
bash = 46347
linq = 45169
visual-studio-2010 = 43907
entity-framework = 43776
perl = 42740
web-services = 42609
matlab = 42112
hibernate = 41410
visual-studio = 40307
wcf = 39948
sql-server-2008 = 39394
mongodb = 38632
asp.net-mvc-3 = 38018
list = 37914
qt = 37505
.htaccess = 37305
css3 = 36505
vba = 36368
sqlite = 36274
actionscript-3 = 35594
file = 35171
twitter-bootstrap = 34911
postgresql = 34757
function = 34747
codeigniter = 33439
api = 32964
class = 32888
scala = 32763
shell = 32407
google-maps = 31961
cocoa = 31744
ipad = 31600
jsp = 31510
cocoa-touch = 30994
tsql = 30976
sockets = 30635
flash = 30555
jquery-ui = 30506
asp.net-mvc-4 = 30278
validation = 30166
security = 30035
delphi = 29758
unit-testing = 29717
rest = 29475
英文:

There is nothing wrong it using existing system package and it fairly simple to retrieve json data over http in go

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

func main() {
	var data struct {
		Items []struct {
			Name              string
			Count             int
			Is_required       bool
			Is_moderator_only bool
			Has_synonyms      bool
		}
	}

	r, _ := http.Get("https://api.stackexchange.com/2.2/tags?page=1&pagesize=100&order=desc&sort=popular&site=stackoverflow")
	defer r.Body.Close()

	dec := json.NewDecoder(r.Body)
	dec.Decode(&data)

	for _, item := range data.Items {
		fmt.Printf("%s = %d\n", item.Name, item.Count)
	}

}

Output go run main.go

java = 781454
javascript = 769128
c# = 744294
php = 692360
android = 617892
jquery = 570461
python = 379608
html = 374617
c++ = 341533
ios = 300992
mysql = 296223
css = 276063
sql = 258178
asp.net = 244833
objective-c = 215095
.net = 202087
iphone = 199749
ruby-on-rails = 190497
c = 166226
ruby = 123840
sql-server = 119341
arrays = 116975
ajax = 109786
regex = 107215
xml = 106705
asp.net-mvc = 101921
json = 101545
wpf = 96016
linux = 92266
django = 88008
database = 86638
eclipse = 79952
vb.net = 78888
r = 78401
xcode = 76326
windows = 74359
angularjs = 73266
string = 71149
html5 = 68094
node.js = 66731
wordpress = 65125
multithreading = 64168
facebook = 62460
excel = 58402
spring = 57380
image = 56798
winforms = 55268
forms = 54263
ruby-on-rails-3 = 52611
osx = 51292
oracle = 50876
git = 50019
performance = 48867
swing = 48768
algorithm = 48258
apache = 47355
bash = 46347
linq = 45169
visual-studio-2010 = 43907
entity-framework = 43776
perl = 42740
web-services = 42609
matlab = 42112
hibernate = 41410
visual-studio = 40307
wcf = 39948
sql-server-2008 = 39394
mongodb = 38632
asp.net-mvc-3 = 38018
list = 37914
qt = 37505
.htaccess = 37305
css3 = 36505
vba = 36368
sqlite = 36274
actionscript-3 = 35594
file = 35171
twitter-bootstrap = 34911
postgresql = 34757
function = 34747
codeigniter = 33439
api = 32964
class = 32888
scala = 32763
shell = 32407
google-maps = 31961
cocoa = 31744
ipad = 31600
jsp = 31510
cocoa-touch = 30994
tsql = 30976
sockets = 30635
flash = 30555
jquery-ui = 30506
asp.net-mvc-4 = 30278
validation = 30166
security = 30035
delphi = 29758
unit-testing = 29717
rest = 29475

huangapple
  • 本文由 发表于 2013年8月1日 23:57:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/17998943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定