本文整理汇总了Golang中net/http.ResponseWriter.Header方法的典型用法代码示例。如果您正苦于以下问题:Golang ResponseWriter.Header方法的具体用法?Golang ResponseWriter.Header怎么用?Golang ResponseWriter.Header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.ResponseWriter
的用法示例。
在下文中一共展示了ResponseWriter.Header方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TodoIndex
func TodoIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(todos); err != nil {
panic(err)
}
}
示例2: showBlockPage
// showBlockPage shows a block page for a page that was blocked by an ACL.
func (c *config) showBlockPage(w http.ResponseWriter, r *http.Request, resp *http.Response, user string, tally map[rule]int, scores map[string]int, rule ACLActionRule) {
w.WriteHeader(http.StatusForbidden)
if c.BlockTemplate == nil {
return
}
data := blockData{
URL: r.URL.String(),
Conditions: rule.Conditions(),
User: user,
Tally: listTally(stringTally(tally)),
Scores: listTally(scores),
Request: r,
Response: resp,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
// Convert rule conditions into category descriptions as much as possible.
var categories []string
for _, acl := range rule.Needed {
categories = append(categories, c.aclDescription(acl))
}
for _, acl := range rule.Disallowed {
categories = append(categories, "not "+c.aclDescription(acl))
}
data.Categories = strings.Join(categories, ", ")
err := c.BlockTemplate.Execute(w, data)
if err != nil {
log.Println("Error filling in block page template:", err)
}
}
示例3: ServeHTTP
// ServeHTTP dispatches the handler registered in the matched route.
//
// When there is a match, the route variables can be retrieved calling
// mux.Vars(request).
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Clean path to canonical form and redirect.
if p := cleanPath(req.URL.Path); p != req.URL.Path {
// Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
// This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
// http://code.google.com/p/go/issues/detail?id=5252
url := *req.URL
url.Path = p
p = url.String()
w.Header().Set("Location", p)
w.WriteHeader(http.StatusMovedPermanently)
return
}
var match RouteMatch
var handler http.Handler
if r.Match(req, &match) {
handler = match.Handler
setVars(req, match.Vars)
setCurrentRoute(req, match.Route)
}
if handler == nil {
handler = r.NotFoundHandler
if handler == nil {
handler = http.NotFoundHandler()
}
}
if !r.KeepContext {
defer context.Clear(req)
}
handler.ServeHTTP(w, req)
}
示例4: WriteSuccess
func WriteSuccess(w http.ResponseWriter, code int) error {
fmt.Println(code)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
item := Item{Item: "success"}
return json.NewEncoder(w).Encode(item)
}
示例5: writeJson
func writeJson(w http.ResponseWriter, r *http.Request, obj interface{}) (err error) {
w.Header().Set("Content-Type", "application/javascript")
var bytes []byte
if r.FormValue("pretty") != "" {
bytes, err = json.MarshalIndent(obj, "", " ")
} else {
bytes, err = json.Marshal(obj)
}
if err != nil {
return
}
callback := r.FormValue("callback")
if callback == "" {
_, err = w.Write(bytes)
} else {
if _, err = w.Write([]uint8(callback)); err != nil {
return
}
if _, err = w.Write([]uint8("(")); err != nil {
return
}
fmt.Fprint(w, string(bytes))
if _, err = w.Write([]uint8(")")); err != nil {
return
}
}
return
}
示例6: postImagesLoad
// POST /images/load
func postImagesLoad(c *context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
// call cluster to load image on every node
wf := NewWriteFlusher(w)
var errorMessage string
errorFound := false
callback := func(what, status string, err error) {
if err != nil {
errorFound = true
errorMessage = err.Error()
sendJSONMessage(wf, what, fmt.Sprintf("Loading Image... : %s", err.Error()))
return
}
if status == "" {
sendJSONMessage(wf, what, "Loading Image...")
} else {
sendJSONMessage(wf, what, fmt.Sprintf("Loading Image... : %s", status))
}
}
c.cluster.Load(r.Body, callback)
if errorFound {
sendErrorJSONMessage(wf, 1, errorMessage)
}
}
示例7: getTripDetails
func getTripDetails(w http.ResponseWriter, r *http.Request) {
tripID := r.URL.Query().Get(":tripID")
fmt.Println(tripID)
var result UberResponse
c, s := getMongoCollection("trips")
defer s.Close()
err := c.Find(bson.M{"_id": bson.ObjectIdHex(tripID)}).One(&result)
if err != nil {
fmt.Println("err = c.Find(bson.M{\"id\": bson.M{\"$oid\":", tripID, "}}).One(&result)")
log.Fatal(err)
}
fmt.Println(result)
//Returning the result to user
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
outputJSON, err := json.Marshal(result)
if err != nil {
w.Write([]byte(`{ "error": "Unable to marshal response. body, outputJSON, err := json.Marshal(t) -- line 110"}`))
panic(err.Error())
}
w.Write(outputJSON)
}
示例8: xml_balance
func xml_balance(w http.ResponseWriter, r *http.Request) {
if !ipchecker(r) {
return
}
w.Header()["Content-Type"] = []string{"text/xml"}
w.Write([]byte("<unspent>"))
wallet.LockBal()
for i := range wallet.MyBalance {
w.Write([]byte("<output>"))
fmt.Fprint(w, "<txid>", btc.NewUint256(wallet.MyBalance[i].TxPrevOut.Hash[:]).String(), "</txid>")
fmt.Fprint(w, "<vout>", wallet.MyBalance[i].TxPrevOut.Vout, "</vout>")
fmt.Fprint(w, "<value>", wallet.MyBalance[i].Value, "</value>")
fmt.Fprint(w, "<inblock>", wallet.MyBalance[i].MinedAt, "</inblock>")
fmt.Fprint(w, "<blocktime>", get_block_time(wallet.MyBalance[i].MinedAt), "</blocktime>")
fmt.Fprint(w, "<addr>", wallet.MyBalance[i].BtcAddr.String(), "</addr>")
fmt.Fprint(w, "<wallet>", html.EscapeString(wallet.MyBalance[i].BtcAddr.Extra.Wallet), "</wallet>")
fmt.Fprint(w, "<label>", html.EscapeString(wallet.MyBalance[i].BtcAddr.Extra.Label), "</label>")
fmt.Fprint(w, "<virgin>", fmt.Sprint(wallet.MyBalance[i].BtcAddr.Extra.Virgin), "</virgin>")
w.Write([]byte("</output>"))
}
wallet.UnlockBal()
w.Write([]byte("</unspent>"))
}
示例9: respondError
func respondError(w http.ResponseWriter, apiErr *apiError, data interface{}) {
w.Header().Set("Content-Type", "application/json")
var code int
switch apiErr.typ {
case errorBadData:
code = http.StatusBadRequest
case errorExec:
code = 422
case errorCanceled, errorTimeout:
code = http.StatusServiceUnavailable
default:
code = http.StatusInternalServerError
}
w.WriteHeader(code)
b, err := json.Marshal(&response{
Status: statusError,
ErrorType: apiErr.typ,
Error: apiErr.err.Error(),
Data: data,
})
if err != nil {
return
}
w.Write(b)
}
示例10: scriptSmoothie
func scriptSmoothie(w http.ResponseWriter, r *http.Request) {
fmt.Println("scriptSmoothie:")
if true {
w.Header().Set("ContentType", "text/javascript")
http.ServeFile(w, r, "smoothie.js")
}
}
示例11: fibHandler
func fibHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("fib:")
if false {
w.Header().Set("ContentType", "text/html")
http.ServeFile(w, r, "demo.js")
}
}
示例12: write
// write renders a returned runtime.Object to the response as a stream or an encoded object. If the object
// returned by the response implements rest.ResourceStreamer that interface will be used to render the
// response. The Accept header and current API version will be passed in, and the output will be copied
// directly to the response body. If content type is returned it is used, otherwise the content type will
// be "application/octet-stream". All other objects are sent to standard JSON serialization.
func write(statusCode int, apiVersion string, codec runtime.Codec, object runtime.Object, w http.ResponseWriter, req *http.Request) {
if stream, ok := object.(rest.ResourceStreamer); ok {
out, flush, contentType, err := stream.InputStream(apiVersion, req.Header.Get("Accept"))
if err != nil {
errorJSONFatal(err, codec, w)
return
}
if out == nil {
// No output provided - return StatusNoContent
w.WriteHeader(http.StatusNoContent)
return
}
defer out.Close()
if len(contentType) == 0 {
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
w.WriteHeader(statusCode)
writer := w.(io.Writer)
if flush {
writer = flushwriter.Wrap(w)
}
io.Copy(writer, out)
return
}
writeJSON(statusCode, codec, object, w, isPrettyPrint(req))
}
示例13: goGetLanguageById
/**
* GET A LANGUAGE BY ITS ID
*/
func goGetLanguageById(w http.ResponseWriter, r *http.Request) {
//parse array of input from request message
vars := mux.Vars(r)
//get id input
var langId string
langId = vars["languageId"]
//execute get method
lang := getLanguageById(langId)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if lang.Id != "" {
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(lang); err != nil {
panic(err)
}
return
}
// If we didn't find it, 404
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
panic(err)
}
}
示例14: readKey
func readKey(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Simply write some test data for now
fmt.Println("reading values")
id := p.ByName("id")
i, _ := strconv.Atoi(id)
u := Data{}
if val, ok := Resp[i]; ok {
fmt.Println(i, val)
u.Key = i
u.Value = val
}
// Marshal provided interface into JSON structure
fmt.Println("before marshalling map :", u)
uj, _ := json.Marshal(u)
fmt.Println("after marshalling map :", u)
// Write content-type, statuscode, payload
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", uj)
}
示例15: json_system
func json_system(w http.ResponseWriter, r *http.Request) {
if !ipchecker(r) {
return
}
var out struct {
Blocks_cached int
Known_peers int
Node_uptime uint64
Net_block_qsize int
Net_tx_qsize int
Heap_size uint64
Heap_sysmem uint64
Qdb_extramem int64
Ecdsa_verify_cnt uint64
}
out.Blocks_cached = len(network.CachedBlocks)
out.Known_peers = peersdb.PeerDB.Count()
out.Node_uptime = uint64(time.Now().Sub(common.StartTime).Seconds())
out.Net_block_qsize = len(network.NetBlocks)
out.Net_tx_qsize = len(network.NetTxs)
out.Heap_size, out.Heap_sysmem = sys.MemUsed()
out.Qdb_extramem = qdb.ExtraMemoryConsumed
out.Ecdsa_verify_cnt = btc.EcdsaVerifyCnt
bx, er := json.Marshal(out)
if er == nil {
w.Header()["Content-Type"] = []string{"application/json"}
w.Write(bx)
} else {
println(er.Error())
}
}