有没有内置的方法可以回复一个HTTP 200的消息,并且没有消息体?

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

Is there a built-in way to respond with a HTTP message 200 and empty body?

问题

我需要一个“check”HTTP端点,它只会回复一个200状态码和空的响应体。我目前的解决方案需要一个单独的函数来实现:

package main

import (
	"net/http"

	"github.com/gorilla/mux"
	"github.com/rs/zerolog/log"
)

func main() {
	r := mux.NewRouter()
	r.Use(mux.CORSMethodMiddleware(r))
	r.HandleFunc("/check", send200).Methods(http.MethodGet)
	err := http.ListenAndServe("0.0.0.0:9991", r)
	if err != nil {
		log.Panic().Msgf("无法启动Web服务器:%v", err)
	}
}

func send200(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, err := w.Write([]byte{})
	if err != nil {
		log.Error().Msgf("无法发送200响应:%v", err)
	}
}

它按预期工作:

curl -v http://localhost:9991/check
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 9991 (#0)
> GET /check HTTP/1.1
> Host: localhost:9991
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 29 Oct 2021 12:11:06 GMT
< Content-Length: 0

是否有一种更简单、可能更符合Go语言风格的方法来直接在路由代码中处理/check,使其成为一行代码?

英文:

I need to have a "check" HTTP endpoint that will just reply with a 200 code and empty body. The solution I have requires a separate function for that:

package main

import (
	&quot;net/http&quot;

	&quot;github.com/gorilla/mux&quot;
	&quot;github.com/rs/zerolog/log&quot;
)

func main() {
	r := mux.NewRouter()
	r.Use(mux.CORSMethodMiddleware(r))
	r.HandleFunc(&quot;/check&quot;, send200).Methods(http.MethodGet)
	err := http.ListenAndServe(&quot;0.0.0.0:9991&quot;, r)
	if err != nil {
		log.Panic().Msgf(&quot;cannot start web server: %v&quot;, err)
	}
}

func send200(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, err := w.Write([]byte{})
	if err != nil {
		log.Error().Msgf(&quot;cannot send 200 answer  %v&quot;, err)
	}
}

It works as expected:

curl -v http://localhost:9991/check
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 9991 (#0)
&gt; GET /check HTTP/1.1
&gt; Host: localhost:9991
&gt; User-Agent: curl/7.55.1
&gt; Accept: */*
&gt;
&lt; HTTP/1.1 200 OK
&lt; Date: Fri, 29 Oct 2021 12:11:06 GMT
&lt; Content-Length: 0

Is there a simpler, possibly more Golangic way to handle /check as a one-liner directly at the routing code?

答案1

得分: 4

使用一个空的处理程序(一个函数体为空的处理函数:{})。如果你没有向响应写入任何内容并且没有设置状态码,HTTP 200 OK 将默认发送回来。

你也可以使用匿名函数(函数字面量):

r.HandleFunc("/check", func(http.ResponseWriter, *http.Request){}).
    Methods(http.MethodGet)
英文:

Use an empty handler (a handler function whose body is empty: {}). If you write nothing to the response writer and set no status code, HTTP 200 OK will be sent back by default.

You may also use an anonymous function (function literal):

r.HandleFunc(&quot;/check&quot;, func(http.ResponseWriter, *http.Request){}).
    Methods(http.MethodGet)

答案2

得分: 2

Go语言没有提供一个处理程序,用于响应200状态和空响应体,但是当处理程序没有调用任何response writer方法时,就会发生这种情况。

如果处理程序没有调用WriteHeader,那么服务器将以200状态码进行响应。显式调用WriteHeader主要用于发送错误代码。

响应体是处理程序写入响应的内容。如果处理程序没有写入响应,则响应为空。

使用一个空函数来发送带有空主体的200响应:

send200 := func(http.ResponseWriter, *http.Request) {}
r.HandleFunc("/check", send200).Methods(http.MethodGet)
英文:

Go does not provide a handler that responds with a 200 status and an empty response body, but that's what happens when a handler does not call any of the response writer methods.

If the handler does not call WriteHeader, then the server responds with a 200 status code. Explicit calls to WriteHeader are primarily used to send error codes.

The response body is whatever the handler writes to the response. The response is empty if the handler does not write to the response.

Use an empty function to send the 200 response with an empty body:

send200 := func(http.ResponseWriter, *http.Request) {}
r.HandleFunc(&quot;/check&quot;, send200).Methods(http.MethodGet)

huangapple
  • 本文由 发表于 2021年10月29日 20:17:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/69768735.html
匿名

发表评论

匿名网友

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

确定