Exemple #1
0
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *FindParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
	var res []error
	if err := r.ParseMultipartForm(32 << 20); err != nil {
		if err != http.ErrNotMultipart {
			return err
		} else if err := r.ParseForm(); err != nil {
			return err
		}
	}
	fds := httpkit.Values(r.Form)

	if err := o.bindXRateLimit(r.Header["X-Rate-Limit"], true, route.Formats); err != nil {
		res = append(res, err)
	}

	fdLimit, fdhkLimit, _ := fds.GetOK("limit")
	if err := o.bindLimit(fdLimit, fdhkLimit, route.Formats); err != nil {
		res = append(res, err)
	}

	fdTags, fdhkTags, _ := fds.GetOK("tags")
	if err := o.bindTags(fdTags, fdhkTags, route.Formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
Exemple #2
0
// ReadRequestOneFile reads the first file from the request (if multipart/),
// or returns the body if not
func ReadRequestOneFile(r *http.Request) (body io.ReadCloser, contentType string, status int, err error) {
	body = r.Body
	contentType = r.Header.Get("Content-Type")
	Log.Debug("ReadRequestOneFile", "ct", contentType)
	if !strings.HasPrefix(contentType, "multipart/") {
		// not multipart-form
		status = 200
		return
	}
	defer r.Body.Close()
	err = r.ParseMultipartForm(1 << 20)
	if err != nil {
		status, err = 405, errors.New("error parsing request as multipart-form: "+err.Error())
		return
	}
	if r.MultipartForm == nil || len(r.MultipartForm.File) == 0 {
		status, err = 405, errors.New("no files?")
		return
	}

Outer:
	for _, fileHeaders := range r.MultipartForm.File {
		for _, fileHeader := range fileHeaders {
			if body, err = fileHeader.Open(); err != nil {
				status, err = 405, fmt.Errorf("error opening part %q: %s", fileHeader.Filename, err)
				return
			}
			contentType = fileHeader.Header.Get("Content-Type")
			break Outer
		}
	}
	status = 200
	return
}
Exemple #3
0
func addItem(w http.ResponseWriter, q *http.Request) {
	//check if SKU exist, if not then generate SKU
	err := q.ParseMultipartForm(32 << 20)

	if err != nil {
		// Handle error
		fmt.Println(err)
	}
	if q.FormValue("SKU") != "" {

		slice := []string{"Image", "Image1", "Image2", "Image3"}

		images := checkifImageneedUpload(q, slice, q.FormValue("SKU"))

		product := Product{
			Title:       q.FormValue("Title"),
			Price:       q.FormValue("Price"),
			SKU:         q.FormValue("SKU"),
			Image:       images,
			Description: q.FormValue("Description"),
		}

		db := dbinit()
		defer db.Close()
		_, err = r.Db("goShop").Table("items").Insert(product).RunWrite(db)
		if err != nil {
			log.Println(err)
		}

		//fmt.Println(q.FormValue("cat"))

		http.Redirect(w, q, "/items", http.StatusFound)
	}

}
Exemple #4
0
func uploadfunc(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.Write([]byte("hello world from host1" + r.Method + "\n"))
		return
	}
	r.ParseMultipartForm(1 << 20)
	//w.Write([]byte("hello world from host1"))
	//w.Write([]byte(r.Header.Get("Content-Type")))
	f, fh, err := r.FormFile("upload")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	filename := fh.Filename
	if strings.Contains(fh.Filename, ":") {
		strtmp := strings.Split(fh.Filename, ":")
		filename = strtmp[len(strtmp)-1]
		fmt.Fprintf(w, "\nchange file name:%s\n", filename)
	} else if strings.Contains(fh.Filename, "/") {
		strtmp := strings.Split(fh.Filename, "/")
		filename = strtmp[len(strtmp)-1]
		fmt.Fprintf(w, "\nchange file name:%s\n", filename)
	}
	fmt.Fprintf(w, "\n%+v\n%s\n", fh.Header, filename)
	file, err := os.OpenFile("/tmp/"+filename, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	io.Copy(file, f)
}
Exemple #5
0
func (sh *SetupHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	if !auth.LocalhostAuthorized(req) {
		fmt.Fprintf(rw,
			"<html><body>Setup only allowed from localhost"+
				"<p><a href='/'>Back</a></p>"+
				"</body></html>\n")
		return
	}
	if req.Method == "POST" {
		err := req.ParseMultipartForm(10e6)
		if err != nil {
			httputil.ServerError(rw, req, err)
			return
		}
		if len(req.Form) > 0 {
			handleSetupChange(rw, req)
			return
		}
		if strings.Contains(req.URL.Path, "restartCamli") {
			err = osutil.RestartProcess()
			if err != nil {
				log.Fatal("Failed to restart: " + err.Error())
			}
		}
	}

	sendWizard(rw, req, false)
}
Exemple #6
0
////////////////////////////////
// Upload files
////////////////////////////////
func uploads(w http.ResponseWriter, r *http.Request) {
	type file struct {
		Name string
	}

	if r.Method == "GET" {
		filez, _ := ioutil.ReadDir("./uploads/")
		files := []file{}
		for _, fn := range filez {
			f := file{}
			f.Name = fn.Name()
			files = append(files, f)
		}
		t.ExecuteTemplate(w, "header", v)
		t.ExecuteTemplate(w, "upload", files)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		f, err := os.OpenFile("./uploads/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer f.Close()
		io.Copy(f, file)
		http.Redirect(w, r, "/kayden/upload", 302)
	}
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdatePetWithFormParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
	var res []error
	if err := r.ParseMultipartForm(32 << 20); err != nil {
		return err
	}
	fds := httpkit.Values(r.Form)

	fdName, fdhkName, _ := fds.GetOK("name")
	if err := o.bindName(fdName, fdhkName, route.Formats); err != nil {
		res = append(res, err)
	}

	rPetID, rhkPetID, _ := route.Params.GetOK("petId")
	if err := o.bindPetID(rPetID, rhkPetID, route.Formats); err != nil {
		res = append(res, err)
	}

	fdStatus, fdhkStatus, _ := fds.GetOK("status")
	if err := o.bindStatus(fdStatus, fdhkStatus, route.Formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
Exemple #8
0
func (this *CacheRequestHandler) delHash(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)

	vars := mux.Vars(r)
	key := vars["key"]

	port := this.master_hashRing.Get(key)
	//	slaver_ip := this.slaver_hashRing[master_ip].Get(key)
	client := this.master_clients[port]

	field := vars["field"]
	vals := strings.Split(field, " ")

	if len(vals) > 0 {
		delvals, err := client.HDel(key, vals...).Result()
		if err == redis.Nil {
			fmt.Fprintf(w, "%v", `{"_type":"1","_msg":"key is not exist"}`)
		} else if err != nil {
			fmt.Fprintf(w, "%v", fmt.Sprintf(`{"_type":"-1","_msg":"%s"}`, err.Error()))
		}
		fmt.Fprintf(w, "%v", fmt.Sprintf(`{"_type":"0","_msg":"%d"}`, delvals))
		return
	}
	fmt.Fprintf(w, "%v", `{"_type":"1","_msg":"field is null"}`)
}
Exemple #9
0
func (this *CacheRequestHandler) ServerAdd(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)

	ports := this.GetFormValue(w, r, "ports")
	if ports == "" {
		fmt.Fprintf(w, "%v", "ERR: ip Empty")
	}

	apiserver := this.GetFormValue(w, r, "apiserver")
	if apiserver == "" {
		fmt.Fprintf(w, "%v", "ERR: apiserver Empty")
	}

	pwd := this.GetFormValue(w, r, "pwd")
	if pwd == "" {
		fmt.Fprintf(w, "%v", "ERR: pwd Empty")
	}

	//	redis_ips := strings.Split(ports, ";")

	//	err := this.addServer(redis_ips, apiserver)
	//	if err != nil {
	//		fmt.Fprintf(w, "%v", "Add Server Failed.")
	//	}
}
Exemple #10
0
func (sh *SetupHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	if !auth.IsLocalhost(req) {
		fmt.Fprintf(rw,
			"<html><body>Setup only allowed from localhost"+
				"<p><a href='/'>Back</a></p>"+
				"</body></html>\n")
		return
	}
	http.Redirect(rw, req, "http://camlistore.org/docs/server-config", http.StatusMovedPermanently)
	return

	// TODO: this file and the code in wizard-html.go is outdated. Anyone interested enough
	// can take care of updating it as something nicer which would fit better with the
	// react UI. But in the meantime we don't link to it anymore.

	if req.Method == "POST" {
		err := req.ParseMultipartForm(10e6)
		if err != nil {
			httputil.ServeError(rw, req, err)
			return
		}
		if len(req.Form) > 0 {
			handleSetupChange(rw, req)
		}
		return
	}

	sendWizard(rw, req, false)
}
Exemple #11
0
func (this *CacheRequestHandler) setZset(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)

	key := this.GetFormValue(w, r, "key")
	if key == "" {
		fmt.Fprintf(w, "%v", "ERR: key Empty")
		return
	}
	val := this.GetFormValue(w, r, "value")
	if val == "" {
		fmt.Fprintf(w, "%v", "ERR: member Empty")
		return
	}

	port := this.master_hashRing.Get(key)
	val_zset, err := ParseZSetValue(val)
	err = this.master_clients[port].ZAdd(key, val_zset).Err()
	if err != nil {
		fmt.Fprintf(w, "%v", "ERR: "+err.Error())
	}

	exp := this.GetFormValue(w, r, "expire")
	if exp != "" {
		err := this.setExpire(key, exp, this.master_clients[port])
		if err != nil {
			fmt.Fprintf(w, "%v", "ERR: "+err.Error())
			return
		}
	}

	fmt.Fprintf(w, "%v", "0")
}
Exemple #12
0
func (s *HTTPServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	req.ParseMultipartForm(1e6)
	data, err := ioutil.ReadAll(req.Body)
	if err != nil {
		panic(err)
	}
	req.Body = ioutil.NopCloser(bytes.NewBuffer(data))
	s.request <- req
	var resp Response
	select {
	case respFunc := <-s.response:
		resp = respFunc(req.URL.Path)
	case <-time.After(s.Timeout):
		const msg = "ERROR: Timeout waiting for test to prepare a response\n"
		fmt.Fprintf(os.Stderr, msg)
		resp = Response{500, nil, []byte(msg)}
	}
	if resp.Headers != nil {
		h := w.Header()
		for k, v := range resp.Headers {
			h.Set(k, v)
		}
	}
	if resp.Status != 0 {
		w.WriteHeader(resp.Status)
	}
	w.Write(resp.Body)
}
Exemple #13
0
func UploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Allowed POST method only", http.StatusMethodNotAllowed)
		return
	}

	err := r.ParseMultipartForm(32 << 20) // maxMemory
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	file, _, err := r.FormFile("upload")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer file.Close()

	f, err := os.Create("/tmp/test.jpg")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer f.Close()

	io.Copy(f, file)
	http.Redirect(w, r, "/show", http.StatusFound)
}
Exemple #14
0
func HttpWrapper(res http.ResponseWriter, req *http.Request, actions []string) (*controllers.BaseController, bool) {
	switch req.Method {
	case "POST":
		if strings.Contains(req.Header.Get("Content-Type"), "multipart/form-data") {
			req.ParseMultipartForm(10000000)
		} else {
			req.ParseForm()
		}
	}
	c := &controllers.BaseController{}
	s, err := sessions.Open("cloaka", req, res)
	if err != nil {
		http.Error(res, "Error creating session", 500)
	}
	c.Session = s
	for _, action := range actions {
		switch action {
		case "guest":
			if c.Session.GetValue("logged") != nil {
				if c.Session.GetValue("logged").(string) != "false" {
					http.Redirect(res, req, "/account/manage", 301)
					return nil, false
				}
			}
		case "csrf":
			csrf := c.Session.GetValue("csrf")
			if csrf == nil {
				http.Redirect(res, req, req.URL.Path, 301)
				return nil, false
			}
			if csrf.(string) != req.PostFormValue("token") {
				http.Redirect(res, req, req.URL.Path, 301)
				return nil, false
			}
			c.Session.SetValue("csrf", controllers.GenerateToken(12))
		case "logged":
			logged := c.Session.GetValue("logged")
			if logged != "true" {
				http.Redirect(res, req, fmt.Sprintf("/account/login?intended=%v", url.QueryEscape(req.URL.Path)), 301)
				return nil, false
			}
			tkn := c.Session.GetValue("token")
			if tkn == nil {
				http.Redirect(res, req, fmt.Sprintf("/account/login?intended=%v", url.QueryEscape(req.URL.Path)), 301)
				return nil, false
			}
			account := models.GetAccountByToken(tkn.(string))
			if account.Name == "" {
				http.Redirect(res, req, fmt.Sprintf("/account/login?intended=%v", url.QueryEscape(req.URL.Path)), 301)
				return nil, false
			}
			c.Account = account
		case "admin":
			if c.Account.Admin == 0 {
				return nil, false
			}
		}
	}
	return c, true
}
Exemple #15
0
func uploadHandler(w http.ResponseWriter, r *http.Request) error {
	// Auth
	if _, err := authenticate(r); err != nil {
		return err
	}
	// Parse
	if err := r.ParseMultipartForm(*serverMaxUploadMem * MB); err != nil {
		return err
	}
	form := r.MultipartForm
	defer form.RemoveAll()
	// For each file
	uploads := form.File["file"]
	blobs := []*blob.Blob{}
	for _, f := range uploads {
		b, err := upload(f)
		if err != nil {
			return err
		}
		blobs = append(blobs, b)
		fmt.Println("created blob", b.ID, "for", b.Name, b.ContentType)
	}
	// Check we actually uploaded something
	if len(blobs) == 0 {
		return errors.New("no blobs stored")
	}
	// Write JSON response
	enc := json.NewEncoder(w)
	if err := enc.Encode(blobs); err != nil {
		return err
	}
	return nil
}
Exemple #16
0
func (this *CacheRequestHandler) setString(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)

	key := this.GetFormValue(w, r, "key")
	if key == "" {
		fmt.Fprintf(w, "%v", "ERR: key Empty")
		return
	}
	val := this.GetFormValue(w, r, "value")
	if val == "" {
		fmt.Fprintf(w, "%v", "ERR: val Empty")
		return
	}
	exp := this.GetFormValue(w, r, "expire")

	name := this.master_hashRing.Get(key)

	err := this.master_clients[name].Set(key, val, 0).Err()
	if err != nil {
		fmt.Fprintf(w, "%v", "ERR: "+err.Error())
	}

	if exp != "" {
		err := this.setExpire(key, exp, this.master_clients[name])
		if err != nil {
			fmt.Fprintf(w, "%v", "ERR: "+err.Error())
			return
		}
	}

	fmt.Fprintf(w, "%v", "0")
}
func DisplayCalculatePage(w http.ResponseWriter, r *http.Request, googleQPXExpressCredentials string) {
	// we need this in order to get POST form data
	r.ParseMultipartForm(15485760)

	postFormData := []byte(r.PostFormValue("flightQueries"))

	flightQueries = make([]data.FlightQuery, 0)
	error := json.Unmarshal(postFormData, &flightQueries)
	utils.CheckErr(error, "Unable to cast received post form data to FlightQueries !")

	// create, initialize and use the template
	uninitializedTemplate := template.New("submit calculation template")
	initializedTempalte, err := uninitializedTemplate.Parse(submitDataHtmlData)
	utils.CheckErr(err, "problem while parsing template")
	err = initializedTempalte.Execute(w, nil)
	utils.CheckErr(err, "problem while executing template")

	for _, query := range flightQueries {
		go performQuery(query, googleQPXExpressCredentials)

		// there is a limit of 10 queries/second/user for QPX Express FREE
		// if we do about 1 query/second/user then it should work !
		time.Sleep(time.Second)
	}
}
Exemple #18
0
func (this *CacheRequestHandler) getKey(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)

	key := this.GetFormValue(w, r, "key")
	if key == "" {
		ErrorParam(w, "key")
		return
	}

	action_type := this.GetFormValue(w, r, "type")
	if action_type == "" {
		ErrorParam(w, "type")
		return
	}
	name := this.master_hashRing.Get(key)
	client := this.master_clients[name]

	if action_type == "exists" {
		val, err := client.Exists(key).Result()
		if err != nil {
			ErrorExcu(w, err)
			return
		}
		ErrorNil(w, val)
		return
	}

	ErrorNil(w, nil)
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UploadFileParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
	var res []error
	if err := r.ParseMultipartForm(32 << 20); err != nil {
		return err
	}
	fds := httpkit.Values(r.Form)

	fdAdditionalMetadata, fdhkAdditionalMetadata, _ := fds.GetOK("additionalMetadata")
	if err := o.bindAdditionalMetadata(fdAdditionalMetadata, fdhkAdditionalMetadata, route.Formats); err != nil {
		res = append(res, err)
	}

	file, fileHeader, err := r.FormFile("file")
	if err != nil {
		res = append(res, errors.New(400, "reading file %q failed: %v", "file", err))
	} else {
		o.File = httpkit.File{Data: file, Header: fileHeader}
	}

	rPetID, rhkPetID, _ := route.Params.GetOK("petId")
	if err := o.bindPetID(rPetID, rhkPetID, route.Formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
Exemple #20
0
// Handler function for fan-out with individual channels
func fanOutWithChannelHandlerFunc(w http.ResponseWriter, r *http.Request) {
	t0 := time.Now()
	// get the content from the POSTed form
	r.ParseMultipartForm(10485760) // max body in memory is 10MB
	file, _, _ := r.FormFile("image")
	defer file.Close()
	tileSize, _ := strconv.Atoi(r.FormValue("tile_size"))
	//
	//   // decode and get original image
	original, _, _ := image.Decode(file)
	bounds := original.Bounds()
	db := cloneTilesDB()

	c1 := cutWithChannel(original, &db, tileSize, bounds.Min.X, bounds.Min.Y, bounds.Max.X/2, bounds.Max.Y/2)
	c2 := cutWithChannel(original, &db, tileSize, bounds.Max.X/2, bounds.Min.Y, bounds.Max.X, bounds.Max.Y/2)
	c3 := cutWithChannel(original, &db, tileSize, bounds.Min.X, bounds.Max.Y/2, bounds.Max.X/2, bounds.Max.Y)
	c4 := cutWithChannel(original, &db, tileSize, bounds.Max.X/2, bounds.Max.Y/2, bounds.Max.X, bounds.Max.Y)

	buf1 := new(bytes.Buffer)
	jpeg.Encode(buf1, original, nil)
	originalStr := base64.StdEncoding.EncodeToString(buf1.Bytes())
	t1 := time.Now()
	images := map[string]string{
		"original": originalStr,
		"part1":    <-c1,
		"part2":    <-c2,
		"part3":    <-c3,
		"part4":    <-c4,
		"duration": fmt.Sprintf("%v ", t1.Sub(t0)),
	}

	t, _ := template.ParseFiles("results_parts.html")
	t.Execute(w, images)
}
Exemple #21
0
func SaveFormFileToTmp(r *http.Request, key string) (string, string, error) {
	// Parse the form.
	if err := r.ParseMultipartForm(MaxMemory); err != nil {
		return "", "", err
	}

	// Create a temporary directory.
	tempDir, err := ioutil.TempDir("", "upload-")
	if err != nil {
		log.Err(err, "When creating a temporary directory")
		return "", "", err
	}

	src, header, err := r.FormFile(key)
	if err != nil {
		return tempDir, "", err
	}

	path := filepath.Join(tempDir, header.Filename)
	dst, err := os.Create(path)
	defer dst.Close()

	if err != nil {
		log.Err(err, "When creating output file: %v", path)
	}

	// Copy the file.
	if _, err = io.Copy(dst, src); err != nil {
		log.Err(err, "When copying to a temporary file")
	}

	return tempDir, path, err
}
Exemple #22
0
func handleForm(r *http.Request) (envs []string, input *bytes.Buffer, err error) {
	input = new(bytes.Buffer)
	r.ParseMultipartForm(5 * 1000 * 1000)

	// If it is not a multipart upload the form can actuall be nil. Stupid design decision
	if r.MultipartForm != nil {
		if fileHeaders, ok := r.MultipartForm.File["stdin"]; ok {
			// If users uploaded a specific file with the name stdin we us this as source
			file, err := fileHeaders[0].Open()
			defer file.Close()

			if err != nil {
				return nil, nil, err
			}

			input.ReadFrom(file)
		}
	} else if stdinField, ok := r.Form["stdin"]; ok {
		// If users have a stdin field we pass that as input to the program
		input.WriteString(stdinField[0])
		delete(r.Form, "stdin")
	}

	// All form arguments are injected into the environment of the executed child program
	for k, v := range r.Form {
		envs = append(envs, fmt.Sprintf("%s=%s", strings.ToUpper(k), strings.Join(v, " ")))
	}

	return
}
Exemple #23
0
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseMultipartForm(2000)
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	formdata := r.MultipartForm
	files := formdata.File["RemoteFile"]
	for i := range files {
		file, err := files[i].Open()
		defer file.Close()
		if err != nil {
			fmt.Fprintln(w, err)
			return
		}
		out, err := os.Create(files[i].Filename)
		defer out.Close()
		if err != nil {
			fmt.Fprintf(w, "create file err!")
			return
		}
		_, err = io.Copy(out, file)
		if err != nil {
			fmt.Fprintln(w, err)
			return
		}
	}
}
Exemple #24
0
/* {{{ func newContext(c web.C, w http.ResponseWriter, r *http.Request) *RESTContext
 *
 */
func newContext(c web.C, w http.ResponseWriter, r *http.Request) (*RESTContext, error) {
	rc := &RESTContext{
		C:        c,
		Response: w,
		Request:  r,
	}

	//request body
	if r.Method != "GET" && r.Method != "HEAD" && r.Method != "DELETE" {
		//rc.Trace("content-type: %s", r.Header.Get("Content-Type"))
		if strings.Contains(r.Header.Get("Content-Type"), "multipart/") {
			rc.Trace("parse multipart")
			if err := r.ParseMultipartForm(env.MaxMemory); err != nil {
				rc.Error("parse multipart form error: %s", err)
				return rc, err
			}
		} else {
			rc.RequestBody, _ = ioutil.ReadAll(r.Body)
			defer r.Body.Close()
			//ReadAll会清空r.Body, 下面需要写回去
			//bf := bytes.NewBuffer(rc.RequestBody)
			//r.Body = ioutil.NopCloser(bf)
		}
	}

	return rc, nil
}
Exemple #25
0
func upload(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method)
	if r.Method == "GET" {
		curtime := time.Now().Unix()
		h := md5.New()
		io.WriterString(h, strconv.FormatInt(curtime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))
		t, _ := template.ParseFiles("upload.gtpl")
		t.Execute(w, token)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		fmt.Fprintf(w, "%v", handler.Header)
		f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer f.Close()
		io.Copy(f.file)
	}
}
// Upload an update file.
func handleUpdatePostRequest(w http.ResponseWriter, r *http.Request) {
	setNoCache(w)
	setJSONHeaders(w)
	r.ParseMultipartForm(1024 * 1024 * 32) // ~32MB update.
	file, handler, err := r.FormFile("update_file")
	if err != nil {
		log.Printf("Update failed from %s (%s).\n", r.RemoteAddr, err.Error())
		return
	}
	defer file.Close()
	// Special hardware builds. Don't allow an update unless the filename contains the hardware build name.
	if (len(globalStatus.HardwareBuild) > 0) && !strings.Contains(handler.Filename, globalStatus.HardwareBuild) {
		w.WriteHeader(404)
		return
	}
	updateFile := fmt.Sprintf("/root/%s", handler.Filename)
	f, err := os.OpenFile(updateFile, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		log.Printf("Update failed from %s (%s).\n", r.RemoteAddr, err.Error())
		return
	}
	defer f.Close()
	io.Copy(f, file)
	log.Printf("%s uploaded %s for update.\n", r.RemoteAddr, updateFile)
	// Successful update upload. Now reboot.
	go delayReboot()
}
Exemple #27
0
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)
	file, handler, err := r.FormFile("files")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer file.Close()

	f, err := os.OpenFile("./uploads/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer f.Close()
	io.Copy(f, file)

	files := Files{
		File{Name: handler.Filename, Type: handler.Header["Content-Type"][0]},
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	if err := json.NewEncoder(w).Encode(files); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

}
func FileUpload(w http.ResponseWriter, r *http.Request) {
	log.Println("METHOD IS " + r.Method + " AND CONTENT-TYPE IS " + r.Header.Get("Content-Type"))

	r.ParseMultipartForm(32 << 20)
	file, handler, err := r.FormFile("file")
	if err != nil {
		json.NewEncoder(w).Encode(Response{err.Error(), true})
		fmt.Println(Response{err.Error(), true})
		return
	}
	defer file.Close()
	// fmt.Fprintf(w, "%v", handler.Header)
	f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		json.NewEncoder(w).Encode(Response{err.Error(), true})
		fmt.Println(Response{err.Error(), true})

		return
	}
	defer f.Close()

	_, err = io.Copy(f, file)
	if err != nil {
		json.NewEncoder(w).Encode(Response{err.Error(), true})
		return
	}
	fmt.Println(Response{"File '" + handler.Filename + "' submited successfully", false})
	json.NewEncoder(w).Encode(Response2{true, handler.Filename + "Server", handler.Filename})
}
Exemple #29
0
// 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()
	}
}
Exemple #30
0
func canonicalRep(req *http.Request) (rep string, err error) {
	err = req.ParseMultipartForm(defaultMaxMemory)
	if err != nil {
		return rep, err
	}
	var repBuff bytes.Buffer

	// HTTP verb (GET, POST,...) uppercased
	repBuff.WriteString(strings.ToUpper(req.Method + "\n"))
	// original URI
	repBuff.WriteString(req.RequestURI + "\n")

	// original headers
	headers := req.Header
	if hmacDate := headers[xHMACDate]; len(hmacDate) > 0 {
		repBuff.WriteString("date:" + hmacDate[0] + "\n")
	} else {
		repBuff.WriteString("date:\n")
	}
	if hmacNonce := headers[xHMACNonce]; len(hmacNonce) > 0 {
		repBuff.WriteString("nonce:" + hmacNonce[0] + "\n")
	} else {
		repBuff.WriteString("nonce:\n")
	}

	// request params
	params := canonicalParams(req.Form)
	for _, v := range params {
		repBuff.WriteString(v + ":" + req.Form[v][0] + "\n")
	}

	rep = repBuff.String()
	return rep, nil
}