dongling4383 2015-09-18 18:57 采纳率: 100%
浏览 31
已采纳

去正确处理切片和字符串

I am using goRequest http://parnurzeal.github.io/gorequest/ to make some HTTP requests against a server process I need to talk to. The authentication process works like this;

send in a GET request with an authentication header set. No problem there, but I need to grab a header from the response and use a returned value to reauthenticate each following request.

The retuned HTTP header looks like this.

Response headers
map[Location:[900767244] Content-Type:[application/xml] Date:[Fri, 18     Sep 2015 18:19:41 GMT] Server:[Apache] X-Frame-Options:[SAMEORIGIN] Set-Cookie:[JSESSIONID=D5C976F5646365FF030DBAD770DA774C; Path=/; Secure; HttpOnly]]

I need to get that location value as it's my session token going forward. If I grap it like this:

session, ok := response.Header["Location"]
if !ok {
    fmt.Println("Did not receive a location header.")
}

fmt.Println("Session: ", session)

I can get it, but it's a slice and NOT a string. How can I get that value as a string so I can pop it back into my request headers going forward? As you can see in the following error:

./login.go:133: cannot use session (type []string) as type string in argument to logoutRequest.Delete

Thanks a lot! Craig

  • 写回答

2条回答 默认 最新

  • douling8772 2015-09-18 19:07
    关注

    If you want one value, use the Header's Get method

    location := response.Header.Get("Location")
    

    This also canonicalizes the header name for you, so that you still get a value even when using slightly different capitalization.

    You only need to index an http.Header value directly when you need to get more than than the first possible value. If you want all values with a canonicalized header name, you can use textproto.CanonicalMIMEHeaderKey

    vals := response.Header[textproto.CanonicalMIMEHeaderKey(header)]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程