doujuanju3076
2017-09-05 09:06
浏览 30
已采纳

无法在net / http golang中处理GET

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条回答 默认 最新

  • doudang4857 2017-09-05 11:15
    已采纳

    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)
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题