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

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条