本文整理汇总了Golang中net/http.Request.ParseMultipartForm方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.ParseMultipartForm方法的具体用法?Golang Request.ParseMultipartForm怎么用?Golang Request.ParseMultipartForm使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Request
的用法示例。
在下文中一共展示了Request.ParseMultipartForm方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: BindRequest
// 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
}
示例2: BindRequest
// 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
}
示例3: addItem
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)
}
}
示例4: ReadRequestOneFile
// 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
}
示例5: ServeHTTP
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)
}
示例6: uploadfunc
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)
}
示例7: uploads
////////////////////////////////
// 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)
}
}
示例8: delHash
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"}`)
}
示例9: ServerAdd
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.")
// }
}
示例10: ServeHTTP
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)
}
示例11: setZset
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")
}
示例12: ServeHTTP
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)
}
示例13: UploadHandler
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)
}
示例14: HttpWrapper
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
}
示例15: uploadHandler
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
}