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 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路