【问题标题】:http.NewRequest() doesn't throw error when request method is invalid请求方法无效时 http.NewRequest() 不会抛出错误
【发布时间】:2021-09-08 12:24:02
【问题描述】:
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是nil,谁能解释一下?

谢谢!

【问题讨论】:

标签: go


【解决方案1】:

bad 不被认为是一个糟糕的 http 方法。

任何包含 !#$%&*+-.0123456789ABCDEFGHIJKLMNOPQRSTUWVXYZ^_`abcdefghijklmnopqrstuvwxyz|~ 字符的非零长度字符串都被认为是有效的

以下是用于验证 HTTP 方法的函数

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-20
    • 2018-06-12
    • 1970-01-01
    • 2014-12-11
    • 2022-01-08
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多