dongliao6491 2018-04-19 04:43
浏览 169
已采纳

从API解析结构

I am trying to access some information stored in a json file via Go. I have two related issues. One is that I'm not sure how to organize my structs and secondly how do I access them via a variable. I'll notate my code to make a little more sense

// To be clear, this is dummy info and I'm linting my actual json
// data. It loads fine, I just don't want to get hung up on this side
{
 "A": {
        "lob": "A",
        "url": [
                 "example.com",
                 "test.com"]
}
 "B": {
        "lob": "B",
        "url": [
                 "example2.com",
                 "test2.com"]

}
}

So the concern is that the structure of the options is identical. I am building this as part of a REST AP. The hope is that users can use http://testapi.com/getdata/A and it will return the urls and name info under A and likewise for B. As is, it loads both of them as separate components of the same struct:

type SiteList struct {
    A struct {
        Lob string   `json:"lob"`
        URL []string `json:"url"`
    } `json:"test"`
    B struct {
        Lob string   `json:"lob"`
        URL []string `json:"url"`
    } `json:"test2"`
}

I can do .A or .B by hand but I'm wondering how to handle it when the requests come in so that my API will only return the data under A or B.

  • 写回答

3条回答 默认 最新

  • donglue1886 2018-04-20 13:22
    关注

    If you're going to consume the API via accessing the API via http://testapi.com/getdata/A or http://testapi.com/getdata/B then A and B can be considered the parameters that drive the behavior of your API.

    If you're passing A, you basically want to access the site data associated with A and if you're passing B, the site data for B should be returned.

    An easy way to organize this data internally is to use a dedicated Go type site which holds Lob and URL and arrange everything in a map via map[string]site, which is initialized on startup of your server.

    You can then dynamically access the parameter given to your API (A or B, but can be easily extended), lookup the site information from the map and, in case it's a valid site, return the corresponding data encoded as JSON.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
        "net/http"
    )
    
    type site struct {
        Lob string   `json:"lob"`
        URL []string `json:"url"`
    }
    
    var sites = map[string]site{
        "A": site{
            Lob: "A",
            URL: []string{
                "example.com",
                "test.com",
            },
        },
        "B": site{
            Lob: "B",
            URL: []string{
                "example2.com",
                "test2.com",
            },
        },
    }
    
    const endpoint = "/getdata/"
    
    func handler(w http.ResponseWriter, r *http.Request) {
        lob := r.URL.Path[len(endpoint):]
        s, ok := sites[lob]
        if !ok {
            w.WriteHeader(http.StatusNotFound)
            return
        }
    
        resp, err := json.Marshal(s)
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
    
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        w.Write(resp)
    }
    
    func main() {
        http.HandleFunc(endpoint, handler)
        log.Fatal(http.ListenAndServe(":8080", nil))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行