本文整理匯總了Golang中github.com/antonholmquist/jason.NewObjectFromReader函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewObjectFromReader函數的具體用法?Golang NewObjectFromReader怎麽用?Golang NewObjectFromReader使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewObjectFromReader函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: SendApiRequest
// Send a request using the supplied authentication tokens.
// Returns an ApiResult that needsto be checked for errors and messages.
func (self *Client) SendApiRequest(url, description string) *ApiResult {
apiResult := &ApiResult{}
apiResult.QueryDescription = description
apiResult.Error = false
r, _ := http.NewRequest("GET", url, nil)
r.SetBasicAuth(self.username, self.apikey)
httpResponse, httpError := self.client.Do(r)
if httpError != nil {
apiResult.HttpError = httpError
return apiResult
}
apiResult.StatusCode = httpResponse.StatusCode
apiResult.Status = httpResponse.Status
jsonResponse, jsonError := jason.NewObjectFromReader(httpResponse.Body)
if jsonError != nil {
apiResult.JsonError = jsonError
return apiResult
}
apiResult.Json = jsonResponse
httpResponse.Body.Close()
obj, notFoundError := jsonResponse.GetObject("error")
if notFoundError == nil {
apiResult.Error = true
apiResult.ErrorMessage = jasonGetString(obj, "message")
apiResult.DeveloperMessage = jasonGetString(obj, "developer_message")
}
return apiResult
}
示例2: CheckAPIKey
// CheckAPIKey performs a test API call with the API key
// provided in the configuration file to determine if the
// service should be enabled.
func (yt *YouTube) CheckAPIKey() error {
var (
response *http.Response
v *jason.Object
err error
)
if viper.GetString("api_keys.youtube") == "" {
return errors.New("No YouTube API key has been provided")
}
url := "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=KQY9zrjPBjo&key=%s"
response, err = http.Get(fmt.Sprintf(url, viper.GetString("api_keys.youtube")))
defer response.Body.Close()
if err != nil {
return err
}
if v, err = jason.NewObjectFromReader(response.Body); err != nil {
return err
}
if v, err = v.GetObject("error"); err == nil {
message, _ := v.GetString("message")
code, _ := v.GetInt64("code")
errArray, _ := v.GetObjectArray("errors")
reason, _ := errArray[0].GetString("reason")
return fmt.Errorf("%d: %s (reason: %s)", code, message, reason)
}
return nil
}
示例3: LoadDevices
func LoadDevices() (devices map[int]*Device, categories map[int]*Category, rooms map[int]*Room) {
res, _ := goreq.Request{
Uri: "http://10.0.1.61:3480/data_request?id=sdata&output_format=json",
}.Do()
json_response, _ := jason.NewObjectFromReader(res.Response.Body)
categories_json, _ := json_response.GetObjectArray("categories")
devices_json, _ := json_response.GetObjectArray("devices")
rooms_json, _ := json_response.GetObjectArray("rooms")
devices = make(map[int]*Device)
categories = make(map[int]*Category)
rooms = make(map[int]*Room)
for _, room_json := range rooms_json {
room := new(Room)
room_bytes, _ := room_json.Marshal()
json.Unmarshal(room_bytes, &room)
rooms[room.Id] = room
}
for _, category_json := range categories_json {
category := new(Category)
category_bytes, _ := category_json.Marshal()
json.Unmarshal(category_bytes, &category)
categories[category.Id] = category
}
for _, device_json := range devices_json {
device := new(Device)
device_bytes, _ := device_json.Marshal()
json.Unmarshal(device_bytes, &device)
device.RoomName = rooms[device.Room].Name
device.CategoryName = categories[device.Category].Name
devices[device.Id] = device
}
return devices, categories, rooms
}
示例4: GetItemInfo
func (ia *itemAttributes) GetItemInfo() (*jason.Object, error) {
var path = ia.bendoServer + "/item/" + ia.item
req, _ := http.NewRequest("GET", path, nil)
if ia.token != "" {
req.Header.Add("X-Api-Key", ia.token)
}
r, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode != 200 {
switch r.StatusCode {
case 404:
return nil, ErrNotFound
case 401:
return nil, ErrNotAuthorized
default:
return nil, fmt.Errorf("Received status %d from Bendo", r.StatusCode)
}
}
v, err := jason.NewObjectFromReader(r.Body)
return v, err
}
示例5: getUploadMeta
func (ia *itemAttributes) getUploadMeta(fileId string) (*jason.Object, error) {
var path = ia.bendoServer + "/upload/" + fileId + "/metadata"
req, _ := http.NewRequest("GET", path, nil)
if ia.token != "" {
req.Header.Add("X-Api-Key", ia.token)
}
req.Header.Add("Accept-Encoding", "application/json")
r, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode != 200 {
switch r.StatusCode {
case 404:
return nil, ErrNotFound
case 401:
return nil, ErrNotAuthorized
default:
return nil, fmt.Errorf("Received status %d from Bendo", r.StatusCode)
}
}
v, err := jason.NewObjectFromReader(r.Body)
return v, err
}
示例6: getTransactionStatus
func (ia *itemAttributes) getTransactionStatus(transaction string) (*jason.Object, error) {
var path = ia.bendoServer + "/transaction/" + transaction
req, err := http.NewRequest("GET", path, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept-Encoding", "application/json")
if ia.token != "" {
req.Header.Add("X-Api-Key", ia.token)
}
resp, err := http.DefaultClient.Do(req)
defer resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
switch resp.StatusCode {
case 404:
return nil, ErrNotFound
case 401:
return nil, ErrNotAuthorized
default:
return nil, fmt.Errorf("Received status %d from Bendo", resp.StatusCode)
}
}
v, err := jason.NewObjectFromReader(resp.Body)
return v, err
}
示例7: GetTracks
// GetTracks uses the passed URL to find and return
// tracks associated with the URL. An error is returned
// if any error occurs during the API call.
func (mc *Mixcloud) GetTracks(url string, submitter *gumble.User) ([]interfaces.Track, error) {
var (
apiURL string
err error
resp *http.Response
v *jason.Object
tracks []interfaces.Track
)
apiURL = strings.Replace(url, "www", "api", 1)
// Track playback offset is not present in Mixcloud URLs,
// so we can safely assume that users will not request
// a playback offset in the URL.
offset, _ := time.ParseDuration("0s")
resp, err = http.Get(apiURL)
defer resp.Body.Close()
if err != nil {
return nil, err
}
v, err = jason.NewObjectFromReader(resp.Body)
if err != nil {
return nil, err
}
id, _ := v.GetString("slug")
trackURL, _ := v.GetString("url")
title, _ := v.GetString("name")
author, _ := v.GetString("user", "username")
authorURL, _ := v.GetString("user", "url")
durationSecs, _ := v.GetInt64("audio_length")
duration, _ := time.ParseDuration(fmt.Sprintf("%ds", durationSecs))
thumbnail, err := v.GetString("pictures", "large")
if err != nil {
// Track has no artwork, using profile avatar instead.
thumbnail, _ = v.GetString("user", "pictures", "large")
}
track := bot.Track{
ID: id,
URL: trackURL,
Title: title,
Author: author,
AuthorURL: authorURL,
Submitter: submitter.Name,
Service: mc.ReadableName,
ThumbnailURL: thumbnail,
Filename: id + ".track",
Duration: duration,
PlaybackOffset: offset,
Playlist: nil,
}
tracks = append(tracks, track)
return tracks, nil
}
示例8: Add
func Add(rend render.Render, req *http.Request) {
params, _ := jason.NewObjectFromReader(req.Body)
name, _ := params.GetString("name")
result, err := group.Add(name)
if err != nil {
rend.JSON(200, helper.Error(err))
return
}
rend.JSON(200, helper.Success(result))
}
示例9: YandexTrans
func YandexTrans(yandexID, in string) string {
escapedIn := url.QueryEscape(in)
retry := 0
Req:
var to string
from := YandexDetect(ydTransAPI, in)
if from == "zh" {
to = "en"
} else {
to = "zh"
}
res, err := goreq.Request{
Uri: fmt.Sprintf("https://translate.yandex.net"+
"/api/v1.5/tr.json/translate?"+
"key=%s&lang=%s&text=%s",
yandexID, to, escapedIn),
Timeout: 17 * time.Second,
}.Do()
if err != nil {
if retry < 2 {
retry++
goto Req
} else {
log.Println("Translation Timeout!")
return "群組娘連接母艦失敗,請稍後重試"
}
}
jasonObj, _ := jason.NewObjectFromReader(res.Body)
code, _ := jasonObj.GetInt64("code")
switch code {
case 200:
text, _ := jasonObj.GetStringArray("text")
return strings.Join(text, "\n")
case 401: //未授權用戶
return "大概男盆友用錯API Key啦,大家快去蛤他!σ`∀´)`"
case 402: //API被屏蔽
return "可憐的群組娘被母艦放逐了X﹏X"
case 403, 404: //請求次數已用完
return "今天彈藥不足,明天再來吧(#°Д°)"
case 413: //文本太長
return "警報!彈藥係統過載!請放寬後重試"
case 422: //文本不可翻譯
return "咦?這是外星語喵?"
case 501: //不支持的語種
return "恭喜你觸發了母艦的迷之G點"
default:
return "發生了理論上不可能出現的錯誤,你是不是穿越了喵?"
}
}
示例10: Check
func Check(rend render.Render, req *http.Request) {
body, _ := jason.NewObjectFromReader(req.Body)
clientsId, _ := body.GetInt64Array("clientsId")
clientList := client.List(clientsId)
results := JSON.Type{}
for _, c := range clientList {
result, err := c.CallRpc("CheckDeployPath", rpc.CheckDeployPathArgs{c.Id, c.DeployPath})
if err != nil {
results[helper.Itoa64(c.Id)] = helper.Error(err)
} else {
results[helper.Itoa64(c.Id)] = result
}
}
rend.JSON(200, helper.Success(results))
}
示例11: Fetch
func (expvars *Expvars) Fetch(addr string) error {
resp, err := expvars.client.Get(addr)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return errors.New("not found")
}
expvars.Object, err = jason.NewObjectFromReader(resp.Body)
if err != nil {
return err
}
return nil
}
示例12: BaiduTranslate
func BaiduTranslate(apiKey, in string) (out, from string) {
in = url.QueryEscape(in)
retry := 0
Req:
res, err := goreq.Request{
Uri: fmt.Sprintf("http://openapi.baidu.com/public/2.0/bmt/translate?"+
"client_id=%s&q=%s&from=auto&to=auto",
apiKey, in),
Timeout: 17 * time.Second,
}.Do()
if err != nil {
if retry < 2 {
retry++
goto Req
} else {
log.Println("Translation Timeout!")
return "群組娘連接母艦失敗,請稍後重試", ""
}
}
jasonObj, _ := jason.NewObjectFromReader(res.Body)
from, _ = jasonObj.GetString("from")
result, err := jasonObj.GetObjectArray("trans_result")
if err != nil {
errCode, _ := jasonObj.GetString("error_code")
switch errCode {
case "52001": //超時
return "轉換失敗,母艦大概是快沒油了Orz", ""
case "52002": //翻譯係統錯誤
return "母艦崩壞中...", ""
case "52003": //未授權用戶
return "大概男盆友用錯API Key啦,大家快去蛤他!σ`∀´)`", ""
case "52004": //必填參數為空
return "彈藥裝填係統泄漏,一定不是奴家的鍋(╯‵□′)╯", ""
default:
return "發生了理論上不可能出現的錯誤,你是不是穿越了喵?", ""
}
}
var outs []string
for k := range result {
tmp, _ := result[k].GetString("dst")
outs = append(outs, tmp)
}
out = strings.Join(outs, "\n")
return out, from
}
示例13: RemoveBackup
func RemoveBackup(rend render.Render, req *http.Request, params martini.Params) {
id := helper.Int64(params["id"])
host, errResponse := getClientWithAliveOrJSONError(id)
if host == nil {
rend.JSON(200, errResponse)
return
}
body, _ := jason.NewObjectFromReader(req.Body)
path, _ := body.GetString("path")
_, err := host.RemoveBackup(path)
if err != nil {
rend.JSON(200, helper.Error(err))
return
}
rend.JSON(200, helper.Success())
}
示例14: getTrack
func (yt *YouTube) getTrack(id string, submitter *gumble.User, offset time.Duration) (bot.Track, error) {
var (
resp *http.Response
err error
v *jason.Object
)
videoURL := "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s"
resp, err = http.Get(fmt.Sprintf(videoURL, id, viper.GetString("api_keys.youtube")))
defer resp.Body.Close()
if err != nil {
return bot.Track{}, err
}
v, err = jason.NewObjectFromReader(resp.Body)
if err != nil {
return bot.Track{}, err
}
items, _ := v.GetObjectArray("items")
if len(items) == 0 {
return bot.Track{}, errors.New("This YouTube video is private")
}
item := items[0]
title, _ := item.GetString("snippet", "title")
thumbnail, _ := item.GetString("snippet", "thumbnails", "high", "url")
author, _ := item.GetString("snippet", "channelTitle")
durationString, _ := item.GetString("contentDetails", "duration")
durationConverted, _ := duration.FromString(durationString)
duration := durationConverted.ToDuration()
return bot.Track{
ID: id,
URL: "https://youtube.com/watch?v=" + id,
Title: title,
Author: author,
Submitter: submitter.Name,
Service: yt.ReadableName,
Filename: id + ".track",
ThumbnailURL: thumbnail,
Duration: duration,
PlaybackOffset: offset,
Playlist: nil,
}, nil
}
示例15: ShortUrl
func ShortUrl(url string) string {
res, err := goreq.Request{
Uri: fmt.Sprintf(
"http://is.gd/create.php?format=json&url=%s",
url),
Timeout: 3 * time.Second,
}.Do()
if err != nil {
loge.Warning("Short Failed!")
return url
}
jasonObj, err := jason.NewObjectFromReader(res.Body)
if err != nil {
return url
}
s, err := jasonObj.GetString("shorturl")
if err != nil {
e, _ := jasonObj.GetString("errormessage")
loge.Warning(e)
return url
}
return s
}