不处理 net/http golang 中的 GET 请求。

huangapple go评论93阅读模式
英文:

Not handling GET in net/http golang

问题

我正在尝试在Golang中关闭处理GET请求,只处理POST请求。这样做可能吗?我这样做的原因是,每当我在localhost:8080上刷新页面多次时,我可以看到Golang分配了越来越多的内存。

以下是我的测试代码:

package main

import (
    "fmt"
    "net/http"
    "encoding/json"
)

type test_struct struct {
    Test string
}

var t test_struct

func handlePOST(rw http.ResponseWriter, req *http.Request) {
    switch req.Method {
    case "POST":
        decoder := json.NewDecoder(req.Body)
        decoder.Decode(&t)
        defer req.Body.Close()
        fmt.Println(t.Test)
    }
}

func main() {
    http.HandleFunc("/", handlePOST)
    http.ListenAndServe(":8080", nil)
}

请注意,上述代码只处理POST请求。

英文:

I am trying to turn off handling GET requests in golang.
I just want to handle POST.

Is it possible to do?

Reason for doing so is that i can see more and more memory being allocated by golang whenever i go to localhost:8080 and refresh page multiple times.

Here is my test code:

package main

import (
  "fmt"
  "net/http"
  "encoding/json"
)
type test_struct struct {
    Test string 
}
var t test_struct

func handlePOST(rw http.ResponseWriter, req *http.Request) {
    switch req.Method {
    case "POST":
    decoder := json.NewDecoder(req.Body)
    decoder.Decode(&t)
    defer req.Body.Close()
    fmt.Println(t.Test)
    }
}
func main() {
    http.HandleFunc("/", handlePOST)
    http.ListenAndServe(":8080", nil)
}

答案1

得分: 2

你不能不处理GET请求,Go的HTTP服务器(或者说它的http.ServeMux)只允许你在将请求分派给处理程序之前指定一个路径模式。HTTP方法相关的路由只能在处理程序级别上发生。

请注意,一些外部的mux库允许你仅向特定的HTTP方法注册处理程序,但是基于此的决策和路由也发生在这些库的“隐藏”处理程序中。

你正在做的是最好的:如果HTTP方法不是你打算处理的方法,只需在处理程序中不做任何操作,或者更好的做法是返回一个http.StatusMethodNotAllowed错误响应:

func myHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Only POST is allowed", http.StatusMethodNotAllowed)
        return
    }

    var t test_struct // 使用局部变量而不是全局变量,否则会出现数据竞争
    decoder := json.NewDecoder(r.Body)
    if err := decoder.Decode(&t); err != nil {
        fmt.Println("Error decoding:", err)
    }
    fmt.Println(t.Test)
}
英文:

You cannot not handle GET requests, Go's HTTP server (or rather its http.ServeMux) only allows you to specify a path pattern before dispatching the request to your handler. HTTP method related routing can only happen at the handler level.

Note that some external mux libraries allow you to register handlers to specific HTTP methods only, but the decision and routing based on that also happens in "hidden" handlers of those libraries.

What you're doing is the best: simply do nothing in the handler if the HTTP method is not the one you intend to handle, or even better: send back a http.StatusMethodNotAllowed error response:

func myHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Only POST is allowed", http.StatusMethodNotAllowed)
        return
    }

    var t test_struct // Use local var not global, else it's a data race
    decoder := json.NewDecoder(r.Body)
    if err := decoder.Decode(&t); err != nil {
        fmt.Println("Error decoding:", err)
    }
    fmt.Println(t.Test)
}

huangapple
  • 本文由 发表于 2017年9月5日 17:06:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/46051085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定