當前位置: 首頁>>代碼示例>>Golang>>正文


Golang http.ResponseWriter類代碼示例

本文整理匯總了Golang中http.ResponseWriter的典型用法代碼示例。如果您正苦於以下問題:Golang ResponseWriter類的具體用法?Golang ResponseWriter怎麽用?Golang ResponseWriter使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了ResponseWriter類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Get

func Get(w http.ResponseWriter, r *http.Request) {
	w.SetHeader("Content-Type", "application/json")
	lock.Lock()
	e := json.NewEncoder(w)
	e.Encode(server)
	lock.Unlock()
}
開發者ID:andradeandrey,項目名稱:stat,代碼行數:7,代碼來源:stats.go

示例2: SetCookie

func (session *Session) SetCookie(w http.ResponseWriter, context appengine.Context) {
	cookie := &http.Cookie{
		Name:  "session",
		Value: session.Key,
	}
	w.Header().Add("Set-Cookie", cookie.String())
}
開發者ID:cmc333333,項目名稱:fragspace,代碼行數:7,代碼來源:session.go

示例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)
}
開發者ID:nicneo925,項目名稱:appscale,代碼行數:30,代碼來源:counter.go

示例4: handle

func (v *jsonView) 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
	}

	d := func() (ret interface{}) {
		defer func() {
			if e := recover(); e != nil {
				if gde, ok := e.(getDataError); ok {
					ret = gde
				} else if ose, ok := e.(os.Error); ok {
					ret = getDataError{http.StatusInternalServerError, ose}
				} else {
					ret = getDataError{http.StatusInternalServerError, os.NewError(fmt.Sprintf("%v", e))}
				}
			}
		}()
		return v.getData(req, s)
	}()

	dd, e := json.Marshal(d)
	if e != nil {
		fmt.Fprintf(w, "{Code: 500, Error: %#v}", e.String())
	} else {
		w.Write(dd)
	}
}
開發者ID:Alexis211,項目名稱:ajstk,代碼行數:29,代碼來源:util.go

示例5: evServer

func evServer(w http.ResponseWriter, r *http.Request) {
	wevs := make(chan store.Event)
	path := r.URL.Path[len("/$events"):]

	glob, err := store.CompileGlob(path + "**")
	if err != nil {
		w.WriteHeader(400)
		return
	}

	rev, _ := Store.Snap()

	go func() {
		walk(path, Store, wevs)
		for {
			ch, err := Store.Wait(glob, rev+1)
			if err != nil {
				break
			}
			ev, ok := <-ch
			if !ok {
				break
			}
			wevs <- ev
			rev = ev.Rev
		}
		close(wevs)
	}()

	websocket.Handler(func(ws *websocket.Conn) {
		send(ws, path, wevs)
		ws.Close()
	}).ServeHTTP(w, r)
}
開發者ID:Br3nda,項目名稱:doozerd,代碼行數:34,代碼來源:web.go

示例6: 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)
	}
}
開發者ID:steliomo,項目名稱:jQuery-File-Upload,代碼行數:25,代碼來源:main.go

示例7: ServeDataItemPage

func ServeDataItemPage(writer http.ResponseWriter, request *http.Request) {
	if strings.Contains(request.Header.Get("Accept"), "application/json") {
		writer.Header().Set("Content-Type", "applicaton/json")
	} else {
		writer.Header().Set("Content-Type", "text/plain")
	}

	stream := StreamByName("ranger")

	log.Printf("Serving full data for '%s'", request.FormValue("q"))
	data := stream.LookupData(request.FormValue("q"))
	if data == nil {
		log.Printf("Failed to find %s", request.FormValue("q"))
		writer.WriteHeader(http.StatusNotFound)
		return
	}

	outputBytes, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		log.Printf("Failed to format data")
		writer.WriteHeader(http.StatusInternalServerError)
		return
	}

	writer.Write(outputBytes)
}
開發者ID:rhettg,項目名稱:scribe_explorer,代碼行數:26,代碼來源:rangerweb.go

示例8: handleIndex

func handleIndex(w http.ResponseWriter, r *http.Request) {

	w.Write([]byte(`<html>
<head>
	<title>Json RPC</title>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
	<script type="text/javascript">
	$(function(){
		$('#button').click(function(){
			var a = $('#a').val();
			var b = $('#b').val();
			var body = '{"jsonrpc": "2.0", "method":"Service.Add","params":['+a+', '+b+'],"id":0}';
			$.post("/json", body ,function(data){
				$('#output').html(data.result);
			}, "json");
		});
	});
	</script>
</head>
<body>
	<h1>Go Ajax Example</h1>
	<input id="a" type="text" name="a" style="width: 50px;" value="5" />
	<span>+</span>
	<input id="b" type="text" name="b" style="width: 50px;" value="7" />
	<input id="button" type="button" value="="/>	
	<span id="output"></span>
</body>
</html>`))
}
開發者ID:niltonkummer,項目名稱:goajax,代碼行數:29,代碼來源:example.go

示例9: InsertTweet

func InsertTweet(w http.ResponseWriter, r *http.Request) {
	query, _ := http.ParseQuery(r.URL.RawQuery)
	signature := Sign([]byte(query["message"][0]))
	tweet := &Tweet{Name: query["name"][0], Message: query["message"][0], Timestamp: query["date"][0], Sig: signature}
	TweetWrite <- tweet
	w.Write([]byte(`"looks good"`))
}
開發者ID:tjgillies,項目名稱:p2pbot,代碼行數:7,代碼來源:ajax.go

示例10: 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+"\"}")
}
開發者ID:alexript,項目名稱:PictureServer,代碼行數:27,代碼來源:main.go

示例11: Symbol

// Symbol looks up the program counters listed in the request,
// responding with a table mapping program counters to function names.
// The package initialization registers it as /debug/pprof/symbol.
func Symbol(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")

	// We don't know how many symbols we have, but we
	// do have symbol information.  Pprof only cares whether
	// this number is 0 (no symbols available) or > 0.
	fmt.Fprintf(w, "num_symbols: 1\n")

	var b *bufio.Reader
	if r.Method == "POST" {
		b = bufio.NewReader(r.Body)
	} else {
		b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
	}

	for {
		word, err := b.ReadSlice('+')
		if err == nil {
			word = word[0 : len(word)-1] // trim +
		}
		pc, _ := strconv.Btoui64(string(word), 0)
		if pc != 0 {
			f := runtime.FuncForPC(uintptr(pc))
			if f != nil {
				fmt.Fprintf(w, "%#x %s\n", pc, f.Name())
			}
		}

		// Wait until here to check for err; the last
		// symbol will have an err because it doesn't end in +.
		if err != nil {
			break
		}
	}
}
開發者ID:richlowe,項目名稱:gcc,代碼行數:38,代碼來源:pprof.go

示例12: authCallback

func authCallback(w http.ResponseWriter, r *http.Request, oldSession *Session) {
	//  We cheat here -- font-end has direct access to the oauth data
	code := r.FormValue("code")
	context := appengine.NewContext(r)
	var userKey datastore.Key
	_, err := memcache.Gob.Get(context, "oauth-code-"+code, &userKey)
	if err != nil {
		w.Write([]byte("Invalid code"))
	} else {
		/*
		   auth := model.NewOAuth2(&userKey)
		   if _, err = datastore.Put(context, datastore.NewIncompleteKey(context, "Authentication", nil), auth); err != nil {
		     context.Errorf("Error saving: %v", err)
		     w.Write([]byte("Error saving: " + err.String()))
		     return
		   }
		   //  replace session cookie
		   oldKey := datastore.NewKey(context, "Session", oldSession.Key, 0, nil)
		   datastore.Delete(context, oldKey)

		   session := NewSession(context)
		   oldSession.Key = session.Key
		   oldSession.Token = auth.Token
		   oldSession.SetCookie(w, context)

		   //  redirect
		*/
	}
}
開發者ID:cmc333333,項目名稱:fragspace,代碼行數:29,代碼來源:authCallback.go

示例13: serveObject

func serveObject(val reflect.Value, w http.ResponseWriter, r *http.Request) os.Error {
	switch r.Method {
	case "HEAD", "GET", "PUT":
	default:
		return nil
		return &BadMethod{r.URL.Path, r.Method, val.Interface()}
	}

	ctype := "application/json"
	// TODO(kevlar): Content type negotiation
	w.Header().Set("Content-Type", ctype)

	if r.Method == "HEAD" {
		return nil
	}

	js, err := json.Marshal(val.Interface())
	if err != nil {
		return &FailedEncode{err, ctype, val.Interface()}
	}

	if _, err := w.Write(js); err != nil {
		return err
	}

	return nil
}
開發者ID:kylelemons,項目名稱:go-resto,代碼行數:27,代碼來源:resource.go

示例14: SetSecureCookie

func SetSecureCookie(rw http.ResponseWriter, name, val, path string, timeout int64) {
	var buf bytes.Buffer

	e := base64.NewEncoder(base64.StdEncoding, &buf)
	e.Write([]byte(val))
	e.Close()

	ts := strconv.Itoa64(time.Seconds())
	data := strings.Join([]string{buf.String(), ts, getCookieSig(buf.Bytes(), ts)}, "|")

	var cookie string

	// Timeout of -1 is a special case that omits the entire 'expires' bit.
	// This is used for cookies which expire as soon as a user's session ends.
	if timeout != -1 {
		t := time.UTC()
		t = time.SecondsToUTC(t.Seconds() + timeout)
		ts = t.Format(time.RFC1123)
		ts = ts[0:len(ts)-3] + "GMT"
		cookie = fmt.Sprintf("%s=%s; expires=%s; path=%s", name, data, ts, path)
	} else {
		cookie = fmt.Sprintf("%s=%s; path=%s", name, data, path)
	}

	if context.Config().Secure {
		cookie += "; secure"
	}

	rw.SetHeader("Set-Cookie", cookie)
}
開發者ID:welterde,項目名稱:mudkip,代碼行數:30,代碼來源:cookies.go

示例15: handleVerify

func handleVerify(conn http.ResponseWriter, req *http.Request) {
	if !(req.Method == "POST" && req.URL.Path == "/camli/sig/verify") {
		httputil.BadRequestError(conn, "Inconfigured handler.")
		return
	}

	req.ParseForm()
	sjson := req.FormValue("sjson")
	if sjson == "" {
		httputil.BadRequestError(conn, "Missing sjson parameter.")
		return
	}

	m := make(map[string]interface{})

	vreq := jsonsign.NewVerificationRequest(sjson, pubKeyFetcher)
	if vreq.Verify() {
		m["signatureValid"] = 1
		m["verifiedData"] = vreq.PayloadMap
	} else {
		errStr := vreq.Err.String()
		m["signatureValid"] = 0
		m["errorMessage"] = errStr
	}

	conn.WriteHeader(http.StatusOK) // no HTTP response code fun, error info in JSON
	httputil.ReturnJson(conn, m)
}
開發者ID:ipeet,項目名稱:camlistore,代碼行數:28,代碼來源:verify.go


注:本文中的http.ResponseWriter類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。