Example #1
1
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
}
Example #2
1
// 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)
			}
		}
	}
}
Example #3
0
func (c GetGraph) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// read the parameters

	vars := mux.Vars(r)
	r.ParseForm()

	typ := vars["type"]

	if len(typ) == 0 {
		w.WriteHeader(400)
		return
	}

	pStart, pEnd := r.Form.Get("start"), r.Form.Get("end")

	if len(pStart) == 0 || len(pEnd) == 0 {
		w.WriteHeader(400)
		return
	}

	// parse the parameters

	start, end := parseTime(pStart), parseTime(pEnd)

	if start.IsZero() || end.IsZero() {
		w.WriteHeader(400)
		return
	}

	// get the data

	values, err := service.GetValuesRange(c.App, start, end, typ)
	if err != nil {
		log.Println("error: while getting values range:", err.Error())
		w.WriteHeader(500)
		return
	}

	// render the data

	var resp getGraphResponse
	resp.Values = make([]timedValue, len(values))

	for i, v := range values {
		resp.Values[i] = timedValue{
			T: v.Time,
			V: v.Value,
		}
	}

	data, err := json.Marshal(resp)
	if err != nil {
		log.Println("error: while marshaling the GetGraph response:", err.Error())
		w.WriteHeader(500)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(data)
}
Example #4
0
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,
		})
	}
}
Example #5
0
// GET /events
func getEvents(c *context, w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		httpError(w, err.Error(), 400)
		return
	}

	var until int64 = -1
	if r.Form.Get("until") != "" {
		u, err := strconv.ParseInt(r.Form.Get("until"), 10, 64)
		if err != nil {
			httpError(w, err.Error(), 400)
			return
		}
		until = u
	}

	c.eventsHandler.Add(r.RemoteAddr, w)

	w.Header().Set("Content-Type", "application/json")

	if f, ok := w.(http.Flusher); ok {
		f.Flush()
	}

	c.eventsHandler.Wait(r.RemoteAddr, until)
}
Example #6
0
func adminornot(w http.ResponseWriter, q *http.Request) {
	err := q.ParseForm()

	if err != nil {
		// Handle error
		fmt.Println(err)
	}

	decoder := schema.NewDecoder()
	adm := new(authUser)

	decoder.Decode(adm, q.PostForm)

	if adm.checkstaffloginpassword() == true {
		session, _ := store.Get(q, sessionname)
		ulin := staffLogedIn{
			UserLogin:     adm.Login,
			IsUserLogedIn: true,
		}

		session.Values["staffLogedIn"] = ulin

		session.Save(q, w)
		render(w, "admin", nil)
	} else {
		newmap := map[string]interface{}{"metatitle": "Registration", "errormessage": "Wrong login or password"}
		render(w, "adminlogin", newmap)
	}

}
Example #7
0
func postLogin(w http.ResponseWriter, r *http.Request) {
	session, _ := store.Get(r, "auth")
	//Temp code. Autologin.
	r.ParseForm()

	if users.Authenticate(r.PostFormValue("username"), r.PostFormValue("password")) {
		session.Values["loggedin"] = true
		session.Save(r, w)
		logger.WithFields(logrus.Fields{
			"method": r.Method,
			"url":    r.URL,
			"client": r.RemoteAddr,
			"user":   r.PostFormValue("username"),
		}).Info("Client logged in.")
		renderer.Render(w, pages.Get(LoginSuccessPage))
	} else {
		logger.WithFields(logrus.Fields{
			"method": r.Method,
			"url":    r.URL,
			"client": r.RemoteAddr,
			"user":   r.PostFormValue("username"),
		}).Info("Client failed to logged in.")
		renderer.Render(w, pages.Get(LoginPage))
	}
}
Example #8
0
// JSON handler for `/delete`:
func deleteJsonHandler(req *http.Request) (result interface{}) {
	if req.Method != "POST" {
		panic(NewHttpError(http.StatusMethodNotAllowed, "Upload requires POST method", fmt.Errorf("Upload requires POST method")))
	}

	// Parse form data:
	if err := req.ParseForm(); err != nil {
		panic(NewHttpError(http.StatusBadRequest, "Error parsing form data", err))
	}
	filename := req.Form.Get("filename")
	if filename == "" {
		panic(NewHttpError(http.StatusBadRequest, "Expecting filename form value", fmt.Errorf("No filename POST value")))
	}

	// Remove the file:
	destPath := path.Join(picsDir, path.Base(filename))
	if err := os.Remove(destPath); err != nil {
		panic(NewHttpError(http.StatusBadRequest, "Unable to delete file", fmt.Errorf("Unable to delete file '%s': %s", destPath, err)))
	}

	return struct {
		Success bool `json:"success"`
	}{
		Success: true,
	}
}
Example #9
0
func handleLogin(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		loginStaticHandler.ServeHTTP(w, r)
	case "POST":
		err := r.ParseForm()
		if err != nil || r.Form.Get("login") == "" {
			log.Println(err)
			http.Error(w, "Error with your request", http.StatusBadRequest)
			return
		}

		login := r.Form.Get("login")
		token := r.Form.Get("token")
		sig := r.Form.Get("sig")
		if token == "" && sig == "" {
			replyWithChallenge(w, login)
		} else {
			checkAuth(w, login, token, sig)
		}
		return
	default:
		http.Error(w, "Verb not understood", http.StatusBadRequest)
	}
}
Example #10
0
func getRequestParams(r *http.Request, urlParams map[string]interface{}) (map[string]interface{}, error) {
	params := make(map[string]interface{})
	err := r.ParseForm()
	if err != nil {
		return nil, err
	}
	for k, v := range r.Form {
		if len(v) >= 1 {
			params[k] = v[0]
		}
	}
	if r.Header.Get("Content-Type") == "application/json" {
		decoder := json.NewDecoder(r.Body)
		requestBodyMap := make(map[string]interface{})
		err = decoder.Decode(&requestBodyMap)
		if err != nil {
			return nil, err
		}
		for k, v := range requestBodyMap {
			params[k] = v
		}
	}
	for k, v := range urlParams {
		params[k] = v
	}
	return params, nil
}
func handleContainerLogs(w http.ResponseWriter, r *http.Request) {
	var outStream, errStream io.Writer
	outStream = ioutils.NewWriteFlusher(w)

	// not sure how to test follow
	if err := r.ParseForm(); err != nil {
		http.Error(w, err.Error(), 500)
	}
	stdout, stderr := getBoolValue(r.Form.Get("stdout")), getBoolValue(r.Form.Get("stderr"))
	if stderr {
		errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
	}
	if stdout {
		outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
	}
	var i int
	if tail, err := strconv.Atoi(r.Form.Get("tail")); err == nil && tail > 0 {
		i = 50 - tail
		if i < 0 {
			i = 0
		}
	}
	for ; i < 50; i++ {
		line := fmt.Sprintf("line %d", i)
		if getBoolValue(r.Form.Get("timestamps")) {
			l := &jsonlog.JSONLog{Log: line, Created: time.Now()}
			line = fmt.Sprintf("%s %s", l.Created.Format(timeutils.RFC3339NanoFixed), line)
		}
		if i%2 == 0 && stderr {
			fmt.Fprintln(errStream, line)
		} else if i%2 == 1 && stdout {
			fmt.Fprintln(outStream, line)
		}
	}
}
Example #12
0
func (s *Server) pubMsg(w http.ResponseWriter, req *http.Request) {
	err := req.ParseForm()
	if err != nil {
		s.log.Error("Parse form failed", err)
		return
	}

	for k, v := range req.PostForm {
		s.log.Debug("%s %s", k, v)
	}

	tslice := req.PostForm["topic"]
	if tslice == nil {
		s.log.Error("No topic in post data")
		return
	}
	topic := tslice[0]

	mslice := req.PostForm["msg"]
	if mslice == nil {
		s.log.Error("No msg in post data")
		return
	}
	msg := mslice[0]

	s.kafka.SendData(topic, msg)
}
Example #13
0
/**
* 修改文章内容
 */
func editArticle(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	id := r.Form["article_id"][0]
	conn := new(Mysql)
	var sql string = "select article_id,title,content,create_time,show_num from article where article_id=" + id + " limit 1"
	rows := conn.connect("blog").selectSql(sql)
	var article_id string
	var title string
	var content string
	var create_time string
	var show_num string
	articleInfo := make(map[string]interface{})
	for rows.Next() {
		rerr := rows.Scan(&article_id, &title, &content, &create_time, &show_num)
		if rerr == nil {
			articleInfo["article_id"] = article_id
			articleInfo["title"] = title
			articleInfo["content"] = content
			articleInfo["create_time"] = create_time
			articleInfo["show_num"] = show_num
		}
	}
	t, _ := template.ParseFiles("admin/editArticle.html")
	t.Execute(w, articleInfo)
}
Example #14
0
/**
* 添加文章
 */
func addArticle(w http.ResponseWriter, r *http.Request) {
	checkManagerAuthority(w, r)

	r.ParseForm()
	retRow, err := r.Form["ret"]

	if err == false {
		data := map[string]string{"msg": ""}
		t, _ := template.ParseFiles("admin/addArticle.html")
		t.Execute(w, data)
	} else {
		ret := retRow[0]
		if ret == "0" {
			data := map[string]string{"msg": "发布成功"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		} else if ret == "1" {
			data := map[string]string{"msg": "文章信息不能为空"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		} else if ret == "2" {
			data := map[string]string{"msg": "prepare执行插入错误"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		} else if ret == "3" {
			data := map[string]string{"msg": "stmt执行插入错误"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		} else if ret == "4" {
			data := map[string]string{"msg": "获取插入id错误"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		}
	}
}
Example #15
0
/**
* 登录处理
 */
func doLogin(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	manageName := r.Form["manage_name"][0]
	password := r.Form["password"][0]
	code := r.Form["code"][0]

	if manageName == "" || password == "" || code == "" {
		io.WriteString(w, "<script type='text/javascript'>location.href='/login'</script>")
	}

	//判断验证码是否正确
	imagecode := getSession(w, r, imageCodeKey)
	if code == imagecode {
		//判断账号和密码是否正确
		userInfo, err := checkLogin(manageName, getSha1(password))
		if err != nil {
			io.WriteString(w, "<script type='text/javascript'>location.href='/login'</script>")
		} else {
			setSession(w, r, manageIdKey, userInfo["manage_id"])
			io.WriteString(w, "<script type='text/javascript'>location.href='/admin'</script>")
		}
	} else {
		io.WriteString(w, "<script type='text/javascript'>location.href='/login'</script>")
	}
}
Example #16
0
func handlerCreateAccount(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		giveFormTemplate("static/create_account.html", w)
	} else if r.Method == "POST" {
		r.ParseForm()
		email := string(template.HTMLEscapeString(r.Form.Get("email")))
		if !validEmail(email) {
			fmt.Fprintf(w, "Please input a valid email")
			return
		}
		username := string(template.HTMLEscapeString(r.Form.Get("username")))
		if username == "" {
			fmt.Fprintf(w, "Username can't be blank")
			return
		}
		password := r.Form.Get("password")
		if !validPassword(password) {
			fmt.Fprintln(w, "Given password does not comply with ",
				"given password directives")
			return
		}
		password = getSha512B64(r.Form.Get("password"))
		if err := AddUser(email, password, username); err != nil {
			fmt.Fprintf(w, "Mail or username already in use or %s\n", err)
			return
		}
		http.Redirect(w, r, "/created", http.StatusFound)
	}
}
Example #17
0
/*
 POST /projects/:projectName/queues/:queueName/messages/delete

 Delete messages from queue

 ids should be be in a JSON encoded array in the "messageIds" form value

 Parameters (Form-Encoded array containing JSON data)
 - messageIds: required, Ids of messages to be deleted

 Response
   - code: 204
   - header: none

 Not found error
   - code: 404
   - body: Queue not found

 Badly formed request error
   - code: 400
   - body: <Error message>

 Misc error (e.g. lost connection to MongoDB)
   - code: 422
   - body: <Error message>
*/
func deleteMessages(w http.ResponseWriter, req *http.Request) {
	q, err := findQueue(w, req)
	if err != nil {
		http.Error(w, "Queue not found", 404)
		return
	}
	if err := req.ParseForm(); err != nil {
		http.Error(w, "Badly formed request (invalid form data)", 400)
		return
	}
	messageIdsJson := req.Form.Get("messageIds")
	if messageIdsJson == "" {
		http.Error(w, "Badly formed request (no 'messageIds' form value)", 400)
		return
	}
	messageIds := make([]string, 0)
	err = json.Unmarshal([]byte(messageIdsJson), &messageIds)
	if err != nil {
		http.Error(w, "Badly formed request ('messageIds' value contains malformed JSON)", 400)
		return
	}
	err = q.DeleteMessages(&messageIds)
	if err != nil {
		http.Error(w, fmt.Sprintf("Could not delete all messages: %v", err), 422)
		return
	}
	w.WriteHeader(204)
}
Example #18
0
// Processes for data for signup and sends email to verify account
func DoSignup(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	vKey := make([]byte, 32)
	n, err := rand.Read(vKey)
	if n != len(vKey) || err != nil {
		log.Println("Could not successfully read from the system CSPRNG.")
	}
	validationKey := hex.EncodeToString(vKey)
	stmt, _ := db.Prepare("insert into signup(username, email, password, validationKey) values(?,?,?,?)")
	_, err = stmt.Exec(r.FormValue("username"), r.FormValue("email"), r.FormValue("password"), validationKey)
	if err != nil {
		// if a validation requests already exists resend email
		if strings.Contains(err.Error(), "1062") {
			log.Println("1062 error")
			stmt, _ := db.Prepare("select validationKey from signup where username=?")
			res := stmt.QueryRow(r.FormValue("username"))
			res.Scan(&validationKey)
			sendVerification(r.FormValue("email"), validationKey)
			http.Redirect(w, r, r.URL.Host+"/resendValidation", 302)
		} else {
			log.Print("Error creating signup record")
			log.Println(err)
		}
	} else {
		sendVerification(r.FormValue("email"), validationKey)
		http.Redirect(w, r, r.URL.Host+"/validationSent", 302)
	}
}
Example #19
0
func (api *API) series(r *http.Request) (interface{}, *apiError) {
	r.ParseForm()
	if len(r.Form["match[]"]) == 0 {
		return nil, &apiError{errorBadData, fmt.Errorf("no match[] parameter provided")}
	}
	res := map[model.Fingerprint]metric.Metric{}

	for _, lm := range r.Form["match[]"] {
		matchers, err := promql.ParseMetricSelector(lm)
		if err != nil {
			return nil, &apiError{errorBadData, err}
		}
		for fp, met := range api.Storage.MetricsForLabelMatchers(
			model.Earliest, model.Latest, // Get every series.
			matchers...,
		) {
			res[fp] = met
		}
	}

	metrics := make([]model.Metric, 0, len(res))
	for _, met := range res {
		metrics = append(metrics, met.Metric)
	}
	return metrics, nil
}
Example #20
0
func setdat(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) //获取请求的方法
	if r.Method == "GET" {
		t, _ := template.ParseFiles("dat.html")
		t.Execute(w, nil)
	} else {
		//请求的是登陆数据,那么执行登陆的逻辑判断
		r.ParseForm()
		for k, v := range r.Form {
			fmt.Println(k, ":", strings.Join(v, " "))
		}
		//clear dat map
		for _, v := range dat {
			for j, _ := range v {
				delete(v, j)
			}
		}
		//reset dat map
		tmp := [...]string{"jsonmap", "cfgmap", "isomap", "md5map", "scriptmap", "resultmap", "servermap", "floppymap"}
		for _, vt := range tmp {
			for k, v := range r.Form[vt+"+fieldid"] {
				dat[vt][v] = r.Form[vt+"+fieldvalue"][k]
			}
		}
		newdataf, _ := os.Create("static/data/log/data.json" + time.Now().Format("20060102150405"))
		dataf, _ := os.Open("static/data/data.json")
		io.Copy(newdataf, dataf)
		defer newdataf.Close()
		defer dataf.Close()
		line, _ := json.Marshal(dat)
		ioutil.WriteFile("static/data/data.json", line, 0)
		http.Redirect(w, r, "/setdat", 302)
	}
}
Example #21
0
func postRegister(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username, password := r.PostFormValue("username"), r.PostFormValue("password")
	if !recaptcher.Verify(*r) {
		logger.WithFields(logrus.Fields{
			"user":  username,
			"error": recaptcher.LastError(),
		}).Error("Failed to verify reCaptcha during registration.")
		w.Write([]byte("Failed to verify the reCaptcha. Please verify that you are human and try again."))
		return
	}

	err := users.Register(username, password)
	switch err {
	case nil:
		//Success
		logger.WithFields(logrus.Fields{
			"method": r.Method,
			"url":    r.URL,
			"client": r.RemoteAddr,
			"user":   username,
		}).Info("User registration")
		renderer.Render(w, pages.Get(RegistrationSuccessPage))
	case ErrUserExists:
		http.Error(w, "The user already exists. Please try again with a different username.", http.StatusPreconditionFailed)
	default:
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Example #22
0
func raw_tx(w http.ResponseWriter, r *http.Request) {
	if !ipchecker(r) {
		return
	}

	defer func() {
		if r := recover(); r != nil {
			fmt.Fprintln(w, "Error")
			if err, ok := r.(error); ok {
				fmt.Fprintln(w, err.Error())
			}
		}
	}()

	r.ParseForm()
	if len(r.Form["id"]) == 0 {
		fmt.Println("No id given")
		return
	}

	txid := btc.NewUint256FromString(r.Form["id"][0])
	fmt.Fprintln(w, "TxID:", txid.String())
	if tx, ok := network.TransactionsToSend[txid.Hash]; ok {
		s, _, _, _, _ := usif.DecodeTx(tx.Tx)
		w.Write([]byte(s))
	} else {
		fmt.Fprintln(w, "Not found")
	}
}
Example #23
0
func shipoptionselect(w http.ResponseWriter, q *http.Request) {
	if q.Method == "POST" {
		err := q.ParseForm()
		if err != nil {
			// Handle error
			fmt.Println(err)
		}
		session, _ := store.Get(q, sessionname)

		order := *session.Values["Order"].(*Order)
		//here put shipping method and price shipping
		order.Shipping = Shipping{
			ShippingMethod: q.FormValue("shippingOfferingId"),
			ShippingCost:   0,
		}
		session.Values["Order"] = order
		session.Save(q, w)
		http.Redirect(w, q, "/payselect", http.StatusFound)
	} else {
		session, _ := store.Get(q, sessionname)
		order := *session.Values["Order"].(*Order)
		newmap := map[string]interface{}{"adress": order.ShippingAdress}
		render(w, "shipoptionselect", newmap)
	}

}
Example #24
0
func register(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	context := appengine.NewContext(req)

	team := Team{
		Date:        time.Now(),
		Name:        req.FormValue("name"),
		Email:       req.FormValue("email"),
		Phonenumber: req.FormValue("phone"),

		PartnerName:        req.FormValue("partner-name"),
		PartnerEmail:       req.FormValue("partner-email"),
		PartnerPhonenumber: req.FormValue("partner-phone"),
		Tech:               strings.Join(req.Form["tech"], ","),
		TeamDescrition:     req.FormValue("descript"),
		TeamWish:           req.FormValue("wish"),
	}
	// TODO make vaildater
	key := datastore.NewIncompleteKey(context, "3rd", getDataStoreKey(context))

	_, err := datastore.Put(context, key, &team)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	} else {
		view.Render(w, "main", RenderData{Mode: "pc"})
		return
	}
}
Example #25
0
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)
}
Example #26
0
func ControllerUpdateAsset(w http.ResponseWriter, r *http.Request) {
	auth.CheckAuthCookie(w, r)
	vars := mux.Vars(r)
	id, _ := strconv.ParseInt(vars["id"], 10, 32)

	if r.Method == "POST" {
		err := r.ParseForm()
		if err != nil {
			// ERROR: Unable to read form data.
			log.Print("ERROR: Bad form data\n")
			http.Redirect(w, r, "/", 302)
		} else {
			asset := new(Asset)
			err := formDecoder.Decode(asset, r.PostForm)
			if err == nil {
				asset.Id = &id
				_ = UpdateAsset(asset)
			} else {
				fmt.Printf("%s\n", r.PostForm)
				fmt.Printf("%s\n", err)
			}

			http.Redirect(w, r, "/assets", 302)
		}
	} else {
		http.Redirect(w, r, "/assets", 302)
	}
}
Example #27
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()
	}
}
Example #28
0
// getSid retrieves session identifier from HTTP Request.
// First try to retrieve id by reading from cookie, session cookie name is configurable,
// if not exist, then retrieve id from querying parameters.
//
// error is not nil when there is anything wrong.
// sid is empty when need to generate a new session id
// otherwise return an valid session id.
func (manager *Manager) getSid(r *http.Request) (string, error) {
	cookie, errs := r.Cookie(manager.config.CookieName)
	if errs != nil || cookie.Value == "" {
		var sid string
		if manager.config.EnableSidInUrlQuery {
			errs := r.ParseForm()
			if errs != nil {
				return "", errs
			}

			sid = r.FormValue(manager.config.CookieName)
		}

		// if not found in Cookie / param, then read it from request headers
		if manager.config.EnableSidInHttpHeader && sid == "" {
			sids, isFound := r.Header[manager.config.SessionNameInHttpHeader]
			if isFound && len(sids) != 0 {
				return sids[0], nil
			}
		}

		return sid, nil
	}

	// HTTP Request contains cookie for sessionid info.
	return url.QueryUnescape(cookie.Value)
}
Example #29
0
func TopicController(w http.ResponseWriter, r *http.Request) {

	var i int64

	templates := template.Must(template.New("topicPage").Parse(views.TopicHTML))

	templates.New("header").Parse(views.HeadTemplateHtml)
	templates.New("navbar").Parse(views.NavbarTemplateHtml)

	//这样可以取得最大的文章号码
	_, i = models.GetAllTopic(w, r)

	log.Printf("Get Topic Count [%d]", i)

	//templates.Parse(views.TopicTemplate)

	if r.Method == "POST" {

		r.ParseForm()

		log.Println(r.Form) //这些信息是输出到服务器端的打印信息

		log.Println(r.Form["title"])

		topic := models.Topic{
			Id:         i + 1,
			Uid:        0,
			Title:      r.Form["title"][0],
			Category:   r.Form["category"][0],
			Content:    r.Form["content"][0],
			Attachment: "",
			Created:    time.Now(),
			Updated:    time.Now(),
			Views:      0,
			Author:     "Bug",
			ReplyCount: 0,
		}

		category := models.Category{
			Title: r.Form["category"][0],
		}

		log.Println(topic)

		models.SaveTopic(w, r, &topic)
		models.SaveCategroy(w, r, &category)
	}

	topnew, _ := models.GetAllTopic(w, r)

	log.Println("in Topic Controller")

	log.Println(topnew)

	err := templates.Execute(w, topnew)
	if err != nil {
		log.Fatal(err)
	}

}
Example #30
0
func (req *stockHttp) Request(ret interface{}) error {
	var hdl *http.Request
	var resp *http.Response
	var err error

	if hdl, err = http.NewRequest("GET", req.url+"?"+req.params.Encode(), nil); err != nil {
		return err
	}

	hdl.Form = req.params
	if err = hdl.ParseForm(); err != nil {
		return err
	}

	for k, v := range req.headers {
		hdl.Header.Add(k, v)
	}

	if resp, err = http.DefaultClient.Do(hdl); err != nil {
		return err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	if err = json.Unmarshal(body, ret); err != nil {
		return err
	}

	return nil
}