dongqing6755
2018-03-11 03:11 阅读 123
已采纳

请求方法无效时,http.NewRequest()不会引发错误

package main

import (
    "log"
    "net/http"
)

func main() {
    // invalid method called "bad"
    req, err := http.NewRequest("bad", "https://www.google.com", nil)
    if err != nil {
        log.Printf("E! got err: %v", err)
    } else {
        log.Printf("I! request method: %s", req.Method)
    }
}

https://play.golang.org/p/NM8_4pkN5uM

err is nil here, can someone explain?

Thanks!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanjizhan9353 duanjizhan9353 2018-03-11 07:02

    bad is not considered as a bad http method.

    Any string of non zero length having characters from !#$%&*+-.0123456789ABCDEFGHIJKLMNOPQRSTUWVXYZ^_`abcdefghijklmnopqrstuvwxyz|~ is considered valid

    Following is the function used to validate a method

    func validMethod(method string) bool {
    
        /*
    
             Method         = "OPTIONS"                ; Section 9.2
    
                            | "GET"                    ; Section 9.3
    
                            | "HEAD"                   ; Section 9.4
    
                            | "POST"                   ; Section 9.5
    
                            | "PUT"                    ; Section 9.6
    
                            | "DELETE"                 ; Section 9.7
    
                            | "TRACE"                  ; Section 9.8
    
                            | "CONNECT"                ; Section 9.9
    
                            | extension-method
    
           extension-method = token
    
             token          = 1*<any CHAR except CTLs or separators>
    
        */
    
        return len(method) > 0 && strings.IndexFunc(method, isNotToken) == -1
    
    }
    
    点赞 评论 复制链接分享

相关推荐