如何使用Go http包发送204 No Content?

Ing*_*ngo 6 google-app-engine http go

我使用Google App Engine上的Go构建了一个小型示例应用程序,在调用不同的URL时发送字符串响应.但是,如何使用Go的http包向客户端发送204 No Content响应?

package hello

import (
    "fmt"
    "net/http"
    "appengine"
    "appengine/memcache"
)

func init() {
    http.HandleFunc("/", hello)
    http.HandleFunc("/hits", showHits)
}

func hello(w http.ResponseWriter, r *http.Request) {
    name := r.Header.Get("name")
    fmt.Fprintf(w, "Hello %s!", name)
}

func showHits(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%d", hits(r))
}

func hits(r *http.Request) uint64 {
    c := appengine.NewContext(r)
    newValue, _ := memcache.Increment(c, "hits", 1, 0)
    return newValue
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*all 15

根据包文档:

func NoContent(w http.ResponseWriter, r *http.Request) {
  // Set up any headers you want here.
  w.WriteHeader(204) // send the headers with a 204 response code.
}
Run Code Online (Sandbox Code Playgroud)

将向客户发送204状态.

  • 你可以说`http.StatusNoContent`而不是204,这是更好的恕我直言. (15认同)