doujuanju3076 2017-09-05 09:06 采纳率: 0%
浏览 32
已采纳

无法在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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大