func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { oa := CheckAuthorized(w, r, false) if oa == nil { return } if r.Method != "POST" { http.Redirect(w, r, "/", http.StatusFound) return } m, _, err := r.FormFile("server") if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } defer m.Close() dst, err := os.Create(deployFileName) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } _, err = io.Copy(dst, m) dst.Close() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } finfo, _ := os.Stat(deployFileName) w.WriteHeader(200) w.Write([]byte("Uploaded: " + humanize.Bytes(uint64(finfo.Size())))) }
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 }
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) } }
// 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) } } } }
// 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 }
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", }) }
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 }
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) } }
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 }
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")) }
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 } }
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) }
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 }
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) }
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) }
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() }
func (srv *Server) createGroup(w http.ResponseWriter, req *http.Request, reqId string) (interface{}, error) { if err := srv.validate(req, []string{"GroupName"}); err != nil { return nil, err } name := req.FormValue("GroupName") path := req.FormValue("Path") for _, group := range srv.groups { if group.Name == name { return nil, &iam.Error{ StatusCode: 409, Code: "EntityAlreadyExists", Message: fmt.Sprintf("Group with name %s already exists.", name), } } } group := iam.Group{ Id: "GROUP " + reqId + "EXAMPLE", Arn: fmt.Sprintf("arn:aws:iam:::123456789012:group%s%s", path, name), Name: name, Path: path, } srv.groups = append(srv.groups, group) return iam.CreateGroupResp{ RequestId: reqId, Group: group, }, nil }
func (srv *Server) getUserPolicy(w http.ResponseWriter, req *http.Request, reqId string) (interface{}, error) { if err := srv.validate(req, []string{"UserName", "PolicyName"}); err != nil { return nil, err } policyName := req.FormValue("PolicyName") userName := req.FormValue("UserName") index := -1 for i, policy := range srv.userPolicies { if policyName == policy.Name && userName == policy.UserName { index = i break } } if index < 0 { return nil, &iam.Error{ StatusCode: 404, Code: "NoSuchEntity", Message: "No such user policy", } } return iam.GetUserPolicyResp{ Policy: srv.userPolicies[index], RequestId: reqId, }, nil }
func invalidate(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) ii := instance_mgt.GetByContext(c) mkk := r.FormValue("mkk") sii := r.FormValue("senderInstanceId") if ll > 2 { aelog.Infof(c, " %s --------- %s\n", sii, mkk) } w.WriteHeader(http.StatusOK) if ii.InstanceID == sii { w.Write([]byte("Its ME " + mkk + "\n")) w.Write([]byte(sii)) } else { w.Write([]byte("got it " + mkk + "\n")) w.Write([]byte(sii + "\n")) w.Write([]byte(ii.InstanceID)) } }
func (srv *Server) serveHTTP(w http.ResponseWriter, req *http.Request) { req.ParseForm() srv.mutex.Lock() defer srv.mutex.Unlock() action := req.FormValue("Action") if action == "" { srv.error(w, &iam.Error{ StatusCode: 400, Code: "MissingAction", Message: "Missing action", }) } if a, ok := actions[action]; ok { reqId := fmt.Sprintf("req%0X", srv.reqId) srv.reqId++ if resp, err := a(srv, w, req, reqId); err == nil { if err := xml.NewEncoder(w).Encode(resp); err != nil { panic(err) } } else { switch err.(type) { case *iam.Error: srv.error(w, err.(*iam.Error)) default: panic(err) } } } else { srv.error(w, &iam.Error{ StatusCode: 400, Code: "InvalidAction", Message: "Invalid action: " + action, }) } }
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 }
func UpdateUser(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) userId, _ := strconv.Atoi(vars["userId"]) user := repository.GetUserById(userId) // oldPassword := r.FormValue("oldPassword") // newPassword := r.FormValue("newPassword") // if oldPassword != "" && newPassword != "" { // result := updatePassword(&user, oldPassword, newPassword) // if result { // w.Write([]byte(`{"result":true}`)) // } else { // w.Write([]byte(`{"result":false}`)) // } // return // } // User is exist displayName := r.FormValue("displayName") email := r.FormValue("email") if displayName != "" { user.DisplayName = displayName } user.Email.Scan(email) repository.UpdateUser(&user) json.NewEncoder(w).Encode(user) }
func (c *ClassifierHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { sample := core.NewSample() if req.Method != "POST" { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } features := req.FormValue("features") if len(features) == 0 { http.Error(w, "need input features", http.StatusInternalServerError) return } fs := make(map[string]float64) err := json.Unmarshal([]byte(features), &fs) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } for k, v := range fs { f := core.Feature{ Id: util.Hash(k), Value: v, } sample.AddFeature(f) } p := c.classifier.Predict(sample) output, err := json.Marshal(map[string]interface{}{ "prediction": p, }) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } fmt.Fprint(w, output) }
func Register(w http.ResponseWriter, r *http.Request) { user := models.User{} if r.FormValue("displayName") != "" { user.DisplayName = r.FormValue("displayName") } else { user.DisplayName = "NULL" } _email := r.FormValue("email") if _email != "" { user.Email.Scan(_email) } if r.FormValue("password") != "" { user.Password = r.FormValue("password") } else { user.Password = "******" } createUserToken(&user) if err := repository.CreateUser(&user).Error; err != nil { w.WriteHeader(http.StatusForbidden) json.NewEncoder(w).Encode(err) return } log.Println(user) json.NewEncoder(w).Encode(user) }
func (api *API) query(r *http.Request) (interface{}, *apiError) { var ts model.Time if t := r.FormValue("time"); t != "" { var err error ts, err = parseTime(t) if err != nil { return nil, &apiError{errorBadData, err} } } else { ts = api.now() } qry, err := api.QueryEngine.NewInstantQuery(r.FormValue("query"), ts) if err != nil { return nil, &apiError{errorBadData, err} } res := qry.Exec() if res.Err != nil { switch res.Err.(type) { case promql.ErrQueryCanceled: return nil, &apiError{errorCanceled, res.Err} case promql.ErrQueryTimeout: return nil, &apiError{errorTimeout, res.Err} } return nil, &apiError{errorExec, res.Err} } return &queryData{ ResultType: res.Value.Type(), Result: res.Value, }, nil }
// Parse the request data based on its content type. func parseForm(r *http.Request) error { if isMultipart(r) == true { return r.ParseMultipartForm(0) } else { return r.ParseForm() } }
func sid(r *http.Request) string { c, _ := r.Cookie("sid") if c != nil { return c.Value } return "" }
func PortBindingCreate(w http.ResponseWriter, r *http.Request) { port := r.FormValue("port") host := r.FormValue("host") hostPort := r.FormValue("host_port") currentHost, err := h.GetCurrentHost() if err != nil { w.Write([]byte("{\"error\": \"" + err.Error() + "\"}")) return } _, binding, err := getPortBinding(port, true) if err != nil { w.Write([]byte("{\"error\": \"" + err.Error() + "\"}")) return } binding.AddBackend(host, hostPort) err = currentHost.Persist() if err != nil { w.Write([]byte("{\"error\": \"" + err.Error() + "\"}")) return } go binding.Start() content, err := json.Marshal(binding) if err != nil { w.Write([]byte("{\"error\": \"" + err.Error() + "\"}")) return } log.Println("exposed " + binding.String()) w.Write(content) }
func (s *errorApiSender) send(ctx context.Context, r *http.Request, message string) { time := time.Now() var errorContext *erpb.ErrorContext if r != nil { errorContext = &erpb.ErrorContext{ HttpRequest: &erpb.HttpRequestContext{ Method: r.Method, Url: r.Host + r.RequestURI, UserAgent: r.UserAgent(), Referrer: r.Referer(), RemoteIp: r.RemoteAddr, }, } } req := erpb.ReportErrorEventRequest{ ProjectName: s.projectID, Event: &erpb.ReportedErrorEvent{ EventTime: ×tamp.Timestamp{ Seconds: time.Unix(), Nanos: int32(time.Nanosecond()), }, ServiceContext: &s.serviceContext, Message: message, Context: errorContext, }, } _, err := s.apiClient.ReportErrorEvent(ctx, &req) if err != nil { log.Println("Error writing error report:", err, "report:", message) } }
func getID(res http.ResponseWriter, req *http.Request) (string, error) { var id, origin string var cookie *http.Cookie // try to get the id from the COOKIE origin = "COOKIE" cookie, err := req.Cookie("session-id") if err == http.ErrNoCookie { // try to get the id from the URL origin = "URL" id := req.FormValue("id") if id == "" { // no id, so create one BRAND NEW origin = "BRAND NEW VIA LOGOUT" log.Println("ID CAME FROM", origin) http.Redirect(res, req, "/logout", http.StatusSeeOther) return id, errors.New("ERROR: redirect to /logout because no session id accessible") } // try to store id for later use in COOKIE cookie = &http.Cookie{ Name: "session-id", Value: id, // Secure: true, HttpOnly: true, } http.SetCookie(res, cookie) } id = cookie.Value log.Println("ID CAME FROM", origin) return id, nil }