本文整理汇总了Golang中net/http.Request类的典型用法代码示例。如果您正苦于以下问题:Golang Request类的具体用法?Golang Request怎么用?Golang Request使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Request类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Validate
func (s *sessionData) Validate(r *http.Request) (validSessionID bool, validXSRFToken bool, err error) {
validSessionID = false
validXSRFToken = false
sessionID, err := r.Cookie("Interlock-Token")
if err != nil {
return
}
XSRFToken := r.Header.Get("X-XSRFToken")
session.Lock()
defer session.Unlock()
if session.SessionID == sessionID.Value {
validSessionID = true
} else {
err = errors.New("invalid session")
}
if session.XSRFToken == XSRFToken {
validXSRFToken = true
} else {
err = errors.New("missing XSRFToken")
}
return
}
示例2: dropSeries
func (api *API) dropSeries(r *http.Request) (interface{}, *apiError) {
r.ParseForm()
if len(r.Form["match[]"]) == 0 {
return nil, &apiError{errorBadData, fmt.Errorf("no match[] parameter provided")}
}
fps := map[model.Fingerprint]struct{}{}
for _, lm := range r.Form["match[]"] {
matchers, err := promql.ParseMetricSelector(lm)
if err != nil {
return nil, &apiError{errorBadData, err}
}
for fp := range api.Storage.MetricsForLabelMatchers(matchers...) {
fps[fp] = struct{}{}
}
}
for fp := range fps {
api.Storage.DropMetricsForFingerprints(fp)
}
res := struct {
NumDeleted int `json:"numDeleted"`
}{
NumDeleted: len(fps),
}
return res, nil
}
示例3: send
func (s *loggingSender) send(ctx context.Context, r *http.Request, message string) {
payload := map[string]interface{}{
"eventTime": time.Now().In(time.UTC).Format(time.RFC3339Nano),
"message": message,
"serviceContext": s.serviceContext,
}
if r != nil {
payload["context"] = map[string]interface{}{
"httpRequest": map[string]interface{}{
"method": r.Method,
"url": r.Host + r.RequestURI,
"userAgent": r.UserAgent(),
"referrer": r.Referer(),
"remoteIp": r.RemoteAddr,
},
}
}
e := logging.Entry{
Severity: logging.Error,
Payload: payload,
}
err := s.logger.LogSync(ctx, e)
if err != nil {
log.Println("Error writing error report:", err, "report:", payload)
}
}
示例4: readRequest
// Read next request from connection.
func (c *conn) readRequest() (r *request, w *response, err error) {
if c.hijacked {
return nil, nil, ErrHijacked
}
c.lr.N = int64(c.server.maxHeaderBytes()) + 4096 /* bufio slop */
var req *http.Request
if req, err = http.ReadRequest(c.buf.Reader); err != nil {
if c.lr.N == 0 {
return nil, nil, errTooLarge
}
return nil, nil, err
}
c.lr.N = noLimit
req.RemoteAddr = c.remoteAddr
w = new(response)
w.conn = c
r = new(request)
r.Request = req
r.w = w
w.reqWantsHttp10KeepAlive = r.wantsHttp10KeepAlive()
w.reqMethod = r.Method
w.reqProtoAtLeast10 = r.ProtoAtLeast(1, 0)
w.reqProtoAtLeast11 = r.ProtoAtLeast(1, 1)
w.reqExpectsContinue = r.expectsContinue()
w.reqContentLength = r.ContentLength
w.header = make(http.Header)
w.contentLength = -1
return r, w, nil
}
示例5: handler
// handler echos the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
mu.Unlock()
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
for k, v := range r.Header {
fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
}
fmt.Fprintf(w, "Host = %q\n", r.Host)
fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)
if err := r.ParseForm(); err != nil {
log.Print(err)
}
for k, v := range r.Form {
fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
// http://localhost:8000/?cycles=20
if k == "cycles" {
cycles := strings.Join(v, "")
ncycles, _ := strconv.Atoi(cycles)
count = count + ncycles
switch coinflip() {
case "heads":
count++
case "tails":
count--
default:
fmt.Fprintf(w, "yo dawg %d\n", count)
}
}
}
}
示例6: DeleteMessageHandler
func (s *Server) DeleteMessageHandler(w http.ResponseWriter, r *http.Request) {
login, err := getYandexLogin(r)
if login == "" || err != nil {
writeError(w, 403, "forbidden")
return
}
subject := r.FormValue("subject")
if subject != "" {
log.Printf("DELETE login=%s subject=%s", login, subject)
err = s.deleteMessagesBySubject(login, subject)
if err != nil {
writeError(w, 500, "failed to delete message: "+err.Error())
return
}
}
id := r.FormValue("id")
if id != "" {
log.Printf("DELETE login=%s id=%s", login, id)
err = s.deleteMessagesByID(login, id)
if err != nil {
writeError(w, 500, "failed to delete message: "+err.Error())
return
}
}
writeResponse(w, 200, map[string]interface{}{
"status": "success",
})
}
示例7: TestServeFile
func TestServeFile(t *testing.T) {
defer afterTest(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ServeFile(w, r, "testdata/file")
}))
defer ts.Close()
var err error
file, err := ioutil.ReadFile(testFile)
if err != nil {
t.Fatal("reading file:", err)
}
// set up the Request (re-used for all tests)
var req http.Request
req.Header = make(http.Header)
if req.URL, err = url.Parse(ts.URL); err != nil {
t.Fatal("ParseURL:", err)
}
req.Method = "GET"
// straight GET
_, body := getBody(t, "straight get", req)
if !bytes.Equal(body, file) {
t.Fatalf("body mismatch: got %q, want %q", body, file)
}
}
示例8: pubHandler
func pubHandler(w http.ResponseWriter, req *http.Request) {
name := req.FormValue("topic")
if name == "" {
http.Error(w, "missing topic", 403)
return
}
size, err := strconv.Atoi(req.FormValue("size"))
if err != nil {
http.Error(w, err.Error(), 403)
return
}
var (
msg *message.Ins
header message.Header
msgs = make([]*message.Ins, 0, size)
)
for !logex.Equal(err, io.EOF) {
msg, err = message.ReadMessage(&header, req.Body, message.RF_DEFAULT)
if err != nil {
break
}
msgs = append(msgs, msg)
}
t, err := getTopic(name)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
t.PutSync(msgs)
w.Write([]byte("hello"))
}
示例9: createUser
func (srv *Server) createUser(w http.ResponseWriter, req *http.Request, reqId string) (interface{}, error) {
if err := srv.validate(req, []string{"UserName"}); err != nil {
return nil, err
}
path := req.FormValue("Path")
if path == "" {
path = "/"
}
name := req.FormValue("UserName")
for _, user := range srv.users {
if user.Name == name {
return nil, &iam.Error{
StatusCode: 409,
Code: "EntityAlreadyExists",
Message: fmt.Sprintf("User with name %s already exists.", name),
}
}
}
user := iam.User{
Id: "USER" + reqId + "EXAMPLE",
Arn: fmt.Sprintf("arn:aws:iam:::123456789012:user%s%s", path, name),
Name: name,
Path: path,
}
srv.users = append(srv.users, user)
return iam.CreateUserResp{
RequestId: reqId,
User: user,
}, nil
}
示例10: onRequest
func onRequest(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
f := &Frame{xrange, yrange}
{
v, err := strconv.ParseFloat(req.FormValue("xr"), 64)
if err == nil {
f.xrange = v
}
v, err = strconv.ParseFloat(req.FormValue("yr"), 64)
if err == nil {
f.yrange = v
}
}
i := &Image{width, height}
{
v, err := strconv.Atoi(req.FormValue("w"))
if err == nil {
i.width = v
}
v, err = strconv.Atoi(req.FormValue("h"))
if err == nil {
i.height = v
}
}
run(w, f, i)
}
示例11: deleteData
func deleteData(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
u := user.Current(ctx)
keyVal := req.FormValue("keyVal")
key, err := datastore.DecodeKey(keyVal)
if err != nil {
http.Error(res, "Invalid data", http.StatusBadRequest)
log.Warningf(ctx, err.Error())
return
}
var l list
err = datastore.Get(ctx, key, &l)
if err != nil {
http.Error(res, "Invalid data", http.StatusBadRequest)
log.Warningf(ctx, err.Error())
return
}
if l.Owner != u.Email {
http.Error(res, "Not authorized to delete this entry", http.StatusUnauthorized)
log.Warningf(ctx, err.Error())
return
}
err = datastore.Delete(ctx, key)
if err != nil {
http.Error(res, "Server Error", http.StatusInternalServerError)
log.Errorf(ctx, err.Error())
return
}
}
示例12: newAuthenticatedRequest
func (c *Client) newAuthenticatedRequest(urlToken string, values url.Values) (*http.Request, error) {
var req *http.Request
var err error
switch c.authMethod {
case AuthMethodClientSecretPost:
values.Set("client_secret", c.creds.Secret)
req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
if err != nil {
return nil, err
}
case AuthMethodClientSecretBasic:
req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
if err != nil {
return nil, err
}
encodedID := url.QueryEscape(c.creds.ID)
encodedSecret := url.QueryEscape(c.creds.Secret)
req.SetBasicAuth(encodedID, encodedSecret)
default:
panic("misconfigured client: auth method not supported")
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return req, nil
}
示例13: foo
func foo(res http.ResponseWriter, req *http.Request) {
templ, error := template.ParseFiles("tpl.gohtml") // Parse template file
if error != nil {
log.Fatalln(error)
}
error = templ.Execute(os.Stdout, nil)
if error != nil {
log.Fatalln(error)
}
cookie, err := req.Cookie("session-fino")
if err != nil {
// id, _ := uuid.NewV4()
cookie = &http.Cookie{
Name: "session-fino",
Value: "0",
// Secure: true,
HttpOnly: true,
}
}
count, _ := strconv.Atoi(cookie.Value)
count++
cookie.Value = strconv.Itoa(count)
fmt.Println(cookie)
http.SetCookie(res, cookie)
templ.ExecuteTemplate(res, "tpl.gohtml", cookie)
}
示例14: handleOauth2Callback
func handleOauth2Callback(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
api := NewGithubAPI(ctx)
// get the session
session := getSession(ctx, req)
state := req.FormValue("state")
code := req.FormValue("code")
if state != session.State {
http.Error(res, "invalid state", 401)
return
}
accessToken, err := api.getAccessToken(state, code)
if err != nil {
http.Error(res, err.Error(), 500)
return
}
api.accessToken = accessToken
username, err := api.getUsername()
if err != nil {
http.Error(res, err.Error(), 500)
return
}
session.Username = username
session.AccessToken = accessToken
putSession(ctx, res, session)
delayedGetStats.Call(ctx, accessToken, username)
http.Redirect(res, req, "/github-info", 302)
}
示例15: PortBindingDelete
func PortBindingDelete(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
port := params.Get(":port")
host := r.FormValue("host")
hostPort := r.FormValue("host_port")
i, binding, err := getPortBinding(port, false)
if err != nil {
w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
return
}
if binding == nil {
w.Write([]byte("{}"))
return
}
if host != "" && hostPort != "" {
binding.RemoveBackend(host, hostPort)
}
currentHost, err := h.GetCurrentHost()
if err != nil {
w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
return
}
if len(binding.Backends) == 0 || (host == "" && hostPort == "") {
binding.Stop()
copy(currentHost.PortBindings[i:], currentHost.PortBindings[i+1:])
currentHost.PortBindings[len(currentHost.PortBindings)-1] = nil
currentHost.PortBindings = currentHost.PortBindings[:len(currentHost.PortBindings)-1]
}
w.Write([]byte("{\"success\": true}"))
currentHost.Persist()
}