本文整理匯總了Golang中http.ResponseWriter.Header方法的典型用法代碼示例。如果您正苦於以下問題:Golang ResponseWriter.Header方法的具體用法?Golang ResponseWriter.Header怎麽用?Golang ResponseWriter.Header使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類http.ResponseWriter
的用法示例。
在下文中一共展示了ResponseWriter.Header方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
u := user.Current(c)
if u == nil {
url, err := user.LoginURL(c, r.URL.String())
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
w.Header().Set("Location", url)
w.WriteHeader(http.StatusFound)
return
}
tok, err := AddClient(c, u.Id)
if err != nil {
http.Error(w, err.String(), 500)
return
}
err = mainTemplate.Execute(w, map[string]string{
"token": tok,
"client_id": u.Id,
"client_email": u.Email,
})
if err != nil {
c.Errorf("mainTemplate: %v", err)
}
}
示例2: homeHandler
func homeHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/html")
url1 := router.NamedRoutes["hello"].URL("salutation", "hello", "name", "world")
url2 := router.NamedRoutes["datastore-session"].URL()
url3 := router.NamedRoutes["memcache-session"].URL()
fmt.Fprintf(w, "Try a <a href='%s'>hello</a>. Or a <a href='%s'>datastore</a> or <a href='%s'>memcache</a> session.", url1, url2, url3)
}
示例3: handle
func handle(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
item, err := memcache.Get(c, r.URL.Path)
if err != nil && err != memcache.ErrCacheMiss {
serveError(c, w, err)
return
}
n := 0
if err == nil {
n, err = strconv.Atoi(string(item.Value))
if err != nil {
serveError(c, w, err)
return
}
}
n++
item = &memcache.Item{
Key: r.URL.Path,
Value: []byte(strconv.Itoa(n)),
}
err = memcache.Set(c, item)
if err != nil {
serveError(c, w, err)
return
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "%q has been visited %d times", r.URL.Path, n)
}
示例4: handle
func handle(w http.ResponseWriter, r *http.Request) {
params, err := url.ParseQuery(r.URL.RawQuery)
check(err)
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add(
"Access-Control-Allow-Methods",
"OPTIONS, HEAD, GET, POST, PUT, DELETE",
)
switch r.Method {
case "OPTIONS":
case "HEAD":
case "GET":
get(w, r)
case "POST":
if len(params["_method"]) > 0 && params["_method"][0] == "DELETE" {
delete(w, r)
} else {
post(w, r)
}
case "DELETE":
delete(w, r)
default:
http.Error(w, "501 Not Implemented", http.StatusNotImplemented)
}
}
示例5: handle
func (v *tplView) handle(w http.ResponseWriter, req *http.Request, s *session) {
if v.checkUniqueURL != "" && req.URL.Path != v.checkUniqueURL {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "<pre>404 page not found</pre>")
return
}
defer func() {
if e := recover(); e != nil {
fmt.Fprintf(w, "%v", e)
log.Printf("Error in handling %v : %v", req.RawURL, e)
}
}()
d := v.getData(req, s)
// fmt.Printf("%#v\n", d) // DEBUG
if ee, ok := d.(getDataError); ok {
w.WriteHeader(ee.Code)
e := tpl["error"].Execute(w, giveTplData{"Sess": s, "Error": ee, "Request": req})
if e != nil {
w.Write([]byte(e.String()))
}
} else if rurl, ok := d.(redirectResponse); ok {
w.Header().Add("Location", string(rurl))
w.WriteHeader(http.StatusFound)
} else {
e := tpl[v.tpl].Execute(w, giveTplData{"Sess": s, "Data": d, "Request": req})
if e != nil {
w.Write([]byte(e.String()))
}
}
}
示例6: PageExecuteJS
// hello world, the web server
func PageExecuteJS(w http.ResponseWriter, req *http.Request) {
url := req.FormValue("url")
js := req.FormValue("js")
header := w.Header()
if url == "" {
log.Printf("ERROR: url is required. (%s)\n", url)
w.WriteHeader(http.StatusInternalServerError)
header.Set("Content-Type", "text/plian;charset=UTF-8;")
io.WriteString(w, "Internal Server Error: please input url.\n")
return
}
if strings.Index(url, "http") != 0 {
log.Printf("ERROR: url is invalid. (%s)\n", url)
w.WriteHeader(http.StatusInternalServerError)
header.Set("Content-Type", "text/plian;charset=UTF-8;")
io.WriteString(w, "Internal Server Error: please input valid url.\n")
return
}
if js == "" {
log.Printf("ERROR: js is required. (%s)\n", url)
w.WriteHeader(http.StatusInternalServerError)
header.Set("Content-Type", "text/plian;charset=UTF-8;")
io.WriteString(w, "Internal Server Error: please input js.\n")
return
}
json := ExecuteJS(url, js)
if len(json) == 0 {
log.Printf("ERROR: failed to execute. (%s)\n", url)
json = []byte("{}")
}
header.Set("Content-Type", "application/json;charset=UTF-8;")
w.Write(json)
}
示例7: ReturnJson
func ReturnJson(conn http.ResponseWriter, data interface{}) {
conn.Header().Set("Content-Type", "text/javascript")
if m, ok := data.(map[string]interface{}); ok {
statusCode := 0
if t, ok := m["error"].(string); ok && len(t) > 0 {
statusCode = http.StatusInternalServerError
}
if t, ok := m["errorType"].(string); ok {
switch t {
case "server":
statusCode = http.StatusInternalServerError
case "input":
statusCode = http.StatusBadRequest
}
}
if statusCode != 0 {
conn.WriteHeader(statusCode)
}
}
bytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
BadRequestError(conn, fmt.Sprintf(
"JSON serialization error: %v", err))
return
}
conn.Write(bytes)
conn.Write([]byte("\n"))
}
示例8: solutionsHandler
func solutionsHandler(w http.ResponseWriter, r *http.Request) {
hint := r.FormValue("hint")
if hint == "" {
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "text/plain;charset=UTF-8;")
io.WriteString(w, "Required parameter 'hint' not received.\n")
return
}
// Use a regexp to find all actual characters
// we already know about
realCharExp := regexp.MustCompile("[^*]")
realChars := realCharExp.FindAllString(hint, -1)
// Replace all '_' in the hint expression for
// 'any character that's not currently known'
newr_str := strings.Replace(hint, "*",
fmt.Sprintf("[^%s]", strings.Join(realChars, "")), -1)
finalExp := regexp.MustCompile(fmt.Sprintf("^%s$", newr_str))
io.WriteString(w, fmt.Sprintf(`<html>
<head><title>Possible Solutions for %s</title></head>
<body><h1>Possible Solutions for %s</h1><ul>`, hint, hint))
// Now go through the word list looking for matches
for i := range wordList.Words() {
if finalExp.MatchString(wordList.Word(i)) {
io.WriteString(w, fmt.Sprintf("<li>%s</li>", wordList.Word(i)))
}
}
io.WriteString(w, "</ul></body></html>")
}
示例9: handle_http
func handle_http(responseWrite http.ResponseWriter, request *http.Request) {
var proxyResponse *http.Response
var proxyResponseError os.Error
proxyHost := strings.Split(request.URL.Path[6:], "/")[0]
fmt.Printf("%s %s %s\n", request.Method, request.RawURL, request.RemoteAddr)
//TODO https
url := "http://" + request.URL.Path[6:]
proxyRequest, _ := http.NewRequest(request.Method, url, nil)
proxy := &http.Client{}
proxyResponse, proxyResponseError = proxy.Do(proxyRequest)
if proxyResponseError != nil {
http.NotFound(responseWrite, request)
return
}
for header := range proxyResponse.Header {
responseWrite.Header().Add(header, proxyResponse.Header.Get(header))
}
contentType := strings.Split(proxyResponse.Header.Get("Content-Type"), ";")[0]
if proxyResponseError != nil {
fmt.Fprintf(responseWrite, "pizda\n")
} else if ReplacemendContentType[contentType] {
body, _ := ioutil.ReadAll(proxyResponse.Body)
defer proxyResponse.Body.Close()
bodyString := replace_url(string(body), "/http/", proxyHost)
responseWrite.Write([]byte(bodyString))
} else {
io.Copy(responseWrite, proxyResponse.Body)
}
}
示例10: printSpamHamJSON
func printSpamHamJSON(w http.ResponseWriter, r *http.Request, key string) {
c := appengine.NewContext(r)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
q := datastore.NewQuery(key)
fmt.Fprintf(w, "[")
first := true
for t := q.Run(c); ; {
var x Entity
_, err := t.Next(&x)
if err == datastore.Done {
break
}
if err != nil {
return
}
if !first {
fmt.Fprintf(w, ", %s", x.Value)
} else {
fmt.Fprintf(w, "%s", x.Value)
first = false
}
}
fmt.Fprintf(w, "]")
}
示例11: registration
func registration(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
u := User{
Name: "TestHendrik",
StartDate: datastore.SecondsToTime(time.Seconds()),
}
if g := user.Current(c); g != nil {
var u2 User
u.Account = g.String()
if err := datastore.Get(c, datastore.NewKey("user", g.String(), 0, nil), &u2); err == datastore.ErrNoSuchEntity {
key, err := datastore.Put(c, datastore.NewKey("user", u.Account, 0, nil), &u)
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "User %q stored %q", u.Account, key)
return
} else {
fmt.Fprintf(w, "User %q is already logged in", g.String())
return
}
} else {
url, err := user.LoginURL(c, r.URL.String())
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
w.Header().Set("Location", url)
w.WriteHeader(http.StatusFound)
return
}
}
示例12: Capture
// hello world, the web server
func Capture(w http.ResponseWriter, req *http.Request) {
url := req.FormValue("url")
header := w.Header()
if url == "" {
log.Printf("ERROR: url is required. (%s)\n", url)
w.WriteHeader(http.StatusInternalServerError)
header.Set("Content-Type", "text/plian;charset=UTF-8;")
io.WriteString(w, "Internal Server Error: please input url.\n")
return
}
if strings.Index(url, "http") != 0 {
log.Printf("ERROR: url is invalid. (%s)\n", url)
w.WriteHeader(http.StatusInternalServerError)
header.Set("Content-Type", "text/plian;charset=UTF-8;")
io.WriteString(w, "Internal Server Error: please input valid url.\n")
return
}
image := CaptureUrl(url)
if len(image) == 0 {
log.Printf("ERROR: failed to capture. (%s)\n", url)
w.WriteHeader(http.StatusInternalServerError)
header.Set("Content-Type", "text/plian;charset=UTF-8;")
io.WriteString(w, "Internal Server Error: Failed to capture.\n")
return
}
header.Set("Content-Type", "image/png")
w.Write(image)
}
示例13: handleGet
func handleGet(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(405)
fmt.Fprintf(w, "405 Method Not Allowed\n\n"+
"To access this amf.go gateway you must use POST requests "+
"(%s received))")
}
示例14: ServeHTTP
func (h *TestHandler) ServeHTTP(w http.ResponseWriter, hr *http.Request) {
h.hit()
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Request-Method", "GET")
fmt.Println("\n=== TestHandler : Requete reçue ====================")
fmt.Println(" Method : " + hr.Method)
fmt.Println(" URL : " + hr.RawURL)
fmt.Println(" Proto : " + hr.Proto)
fmt.Printf(" ContentLength : %d\n", hr.ContentLength)
fmt.Println(" UserAgent : " + hr.UserAgent)
fmt.Println(" Header :")
for key, value := range hr.Header {
fmt.Printf(" %s=%v\n", key, value)
}
b, e := ioutil.ReadAll(hr.Body)
if e != nil {
fmt.Println("Erreur lecture :")
fmt.Println(e)
}
s := string(b)
fmt.Print(s)
fmt.Fprint(w, "Bien reçu")
}
示例15: uploadUser
func uploadUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
// No upload; show the upload form.
uploadUserTemplate.Execute(w, nil)
return
}
f, _, err := r.FormFile("image")
errors.Check(err)
defer f.Close()
// Grab the image data
i, _, err := image.Decode(f)
errors.Check(err)
var key string = keyOf()
// store image
i = picstore.Store(key, i, 320, "userimg")
i = picstore.Store(key, i, 180, "userthumb")
// generate result
w.Header().Set("Content-Type", "application/json")
w.Header().Set("cache-control", "no-cache")
w.Header().Set("Expires", "-1")
fmt.Fprintf(w, "{\"profilePicUrl\":\"uimg?id="+key+"\",\"profileThumbUrl\":\"utmb?id="+key+"\"}")
}