doutian3010 2017-06-03 22:32
浏览 81
已采纳

如何从Go http.Request中检索对象?

I have a working app that recieves HTTP GET parameters. They've been Strings and ints until now and it has worked fine getting each field using

http.Request.FormValue("field")

But now I've added an array of simple objects in the parameters and I don't know how to transform it to a slice of Go structs.

The array in question is

mods:[{
    name : x,
    max : 1,
    min : 2
 },{
    name:y,...
 }]

So I'm not sure how to proceed to map it to a Go struct. Should I create the struct first and map the result of r.FormValue using JSON?

  • 写回答

2条回答 默认 最新

  • dongqindu8110 2017-06-04 10:32
    关注

    Let's say you want to fetch a set of github users and want to print their nicknames (Login field in api.github.com).

    Given a User array example:

    [{
      "login": "simonjefford",
      "id": 136,
      "avatar_url": "https://avatars1.githubusercontent.com/u/136?v=3",
      "gravatar_id": "",
      "url": "https://api.github.com/users/simonjefford",
      "html_url": "https://github.com/simonjefford",
      "followers_url": "https://api.github.com/users/simonjefford/followers",
      "following_url": "https://api.github.com/users/simonjefford/following{/other_user}",
      "gists_url": "https://api.github.com/users/simonjefford/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/simonjefford/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/simonjefford/subscriptions",
      "organizations_url": "https://api.github.com/users/simonjefford/orgs",
      "repos_url": "https://api.github.com/users/simonjefford/repos",
      "events_url": "https://api.github.com/users/simonjefford/events{/privacy}",
      "received_events_url": "https://api.github.com/users/simonjefford/received_events",
      "type": "User",
      "site_admin": false
    }]
    

    You need a proper struct to handle it:

    type Users []struct {
      Login string `json:"login"`
      ID int `json:"id"`
      AvatarURL string `json:"avatar_url"`
      GravatarID string `json:"gravatar_id"`
      URL string `json:"url"`
      HTMLURL string `json:"html_url"`
      FollowersURL string `json:"followers_url"`
      FollowingURL string `json:"following_url"`
      GistsURL string `json:"gists_url"`
      StarredURL string `json:"starred_url"`
      SubscriptionsURL string `json:"subscriptions_url"`
      OrganizationsURL string `json:"organizations_url"`
      ReposURL string `json:"repos_url"`
      EventsURL string `json:"events_url"`
      ReceivedEventsURL string `json:"received_events_url"`
      Type string `json:"type"`
      SiteAdmin bool `json:"site_admin"`
    }
    

    I suggest you to use json-to-go to have a nice a clean struct given a json.

    Then you can do the following:

    package main
    
    import (
      "fmt"
      "encoding/json"
      "net/http"
      "log"
      "io/ioutil"
    )
    
    func main() {
    
      response, err := http.Get("https://api.github.com/users?since=135")
      if err != nil {
         log.Fatal(err)
      } else {
    
        defer response.Body.Close()
        users := UnmarshalUsers(response)
        for _, u := range users {
            //Print each user's Login nickname
            fmt.Println(u.Login)
        }
    
      }
    
    }
    

    Where UnmarshalUsers is

    func UnmarshalUsers(r *http.Response) Users {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            panic(err)
        }
        var users Users
        err = json.Unmarshal(body, &users)
        if err != nil {
            panic(err)
        }
    
        return users
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程