doukanmang3687 2014-09-04 16:34
浏览 77
已采纳

golang地图比较:部分匹配

I am looking to compare received HTTP request headers with a map of expected headers being stored as part of a struct:

type Request struct {
    URI    string
    Method string
    Headers map[string]interface{}
}

I need to make sure that the Headers defined in the struct exist in the incoming request. I don't care if there are extra headers I wasn't expecting, but all headers stored in the struct must be present.

Is there a golang convention for determining whether all items in a map exist in another map? Some example data:

{
  "expected_headers": {
    "Content-Type": ["application/json"],
    "Accept-Encoding": ["gzip, deflate"]
  },
  "received_headers": {
    "Content-Type": ["application/json"],
    "Accept-Encoding": ["gzip, deflate"],
    "Accept": ["application/json"]
}

That is a positive example: i.e. the result of testing if the expected headers are present in the received headers should be True.

I know I could loop over the set of expected_headers and look for each of them in received_headers. However, I'm hoping there is a more elegant way to accomplish the same thing.


Based on the comments, I have added my solution. I freely admit that I'm brand new to Go (though I've been coding in many different languages for decades). My solution does not seem elegant to me. Better solutions welcome!

func contains(theSlice []string, theValue string) bool {
    for _, value := range theSlice {
        if value == theValue {
            return true
        }
    }
    return false
}

func slicesMatch(slice1 []string, slice2 []string) bool {
    for _, value := range slice1 {
        if !(contains(slice2, value)) {
            return false
        }
    }
    return true
}

func headersMatch(expected map[string][]string, actual http.Header) bool {
    for key, value := range expected {
        if !(slicesMatch(value, actual[key])) {
            return false
        }
    }
    return true
}
  • 写回答

1条回答 默认 最新

  • doufei5537 2014-09-04 16:49
    关注

    Is there a golang convention for determining whether all items in a map exist in another map?

    No, there isn't. You will have to loop and check one at a time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样