doukanmang3687
doukanmang3687
2014-09-04 16:34

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 doufei5537 7年前

    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.

    点赞 评论 复制链接分享

相关推荐