コード例 #1
0
ファイル: rule.go プロジェクト: bluefchen/studygolang
func ModifyRuleHandler(rw http.ResponseWriter, req *http.Request) {
	var data = make(map[string]interface{})

	if req.PostFormValue("submit") == "1" {
		user, _ := filter.CurrentUser(req)

		errMsg, err := service.ModifyTopic(user, req.PostForm)
		if err != nil {
			data["ok"] = 0
			data["error"] = errMsg
		} else {
			data["ok"] = 1
			data["msg"] = "修改成功"
		}
	} else {
		topic, replies, err := service.FindTopicByTid(req.FormValue("tid"))

		if err != nil {
			rw.WriteHeader(http.StatusInternalServerError)
			return
		}

		// 设置内容模板
		req.Form.Set(filter.CONTENT_TPL_KEY, "/template/admin/topic/modify.html")
		data["topic"] = topic
		data["replies"] = replies
		data["nodes"] = service.GenNodes()
	}

	filter.SetData(req, data)
}
コード例 #2
0
ファイル: imagemagick.go プロジェクト: qwo/abelana-gcp
func notificationHandler(w http.ResponseWriter, r *http.Request) {
	bucket, name := r.PostFormValue("bucket"), r.PostFormValue("name")
	if bucket == "" || name == "" {
		http.Error(w, "missing bucket or name", http.StatusBadRequest)
		return
	}

	if ok, err := authorized(r.Header.Get("Authorization")); !ok {
		if err != nil {
			log.Printf("authorize: %v", err)
		}
		http.Error(w, "you're not authorized", http.StatusForbidden)
		return
	}

	start := time.Now()
	defer func() { log.Printf("%v: processed in %v", name, time.Since(start)) }()

	if err := processImage(bucket, name); err != nil {
		// TODO: should this remove uploaded images?
		log.Println(err.Error())
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := notifyDone(name); err != nil {
		log.Println(err.Error())
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
コード例 #3
0
ファイル: routes.go プロジェクト: Victorystick/authprox
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)
	}
}
コード例 #4
0
// Updates the display-station mapping for a single display.
func FieldPostHandler(w http.ResponseWriter, r *http.Request) {
	displayId := r.PostFormValue("displayId")
	allianceStation := r.PostFormValue("allianceStation")
	mainArena.allianceStationDisplays[displayId] = allianceStation
	mainArena.matchLoadTeamsNotifier.Notify(nil)
	http.Redirect(w, r, "/setup/field", 302)
}
コード例 #5
0
ファイル: main.go プロジェクト: ieee0824/slack-invite-oss
func viewInvite(w http.ResponseWriter, r *http.Request) {
	mail := r.PostFormValue("mail")
	conf, err := loadConf()
	if err != nil {
		log.Fatalln(err)
	}

	client := &http.Client{}
	data := url.Values{
		"email":      {mail},
		"token":      {conf.Token},
		"set_active": {"true"},
	}

	resp, err := client.Post(
		"https://"+conf.URL+"/api/users.admin.invite",
		"application/x-www-form-urlencoded",
		strings.NewReader(data.Encode()),
	)
	if err != nil {
		log.Fatalln(err)
	}
	body, _ := ioutil.ReadAll(resp.Body)

	var status map[string]interface{}
	json.Unmarshal(body, &status)
	fmt.Println(status["ok"])
	statusOk := fmt.Sprint(status["ok"])

	if statusOk == "true" {
		fmt.Fprintf(w, mail+"に招待状を送信しました.")
	} else {
		fmt.Fprintf(w, "失敗した。失敗した。失敗した。"+fmt.Sprint(status["error"]))
	}
}
コード例 #6
0
ファイル: webcompile.go プロジェクト: fnasim/WebCompile
func compile(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-type", "application/json")

	if len(CorsHeader) > 0 {
		w.Header().Set("Access-Control-Allow-Origin", CorsHeader)
	}
	// language := r.PostFormValue("language")
	language := "C#"
	code := r.PostFormValue("code")

	codeSize := len(code)
	if codeSize <= 0 || codeSize > MaximumCodeSizeInBytes {
		compileResponseError(w, "Code must be greater than 0 and less than max limit")
		return
	}

	out, err, elapsed, timedOut := executeCodeOnDocker(language, code)

	compileResponse(
		w,
		out,
		int64(elapsed/time.Millisecond),
		err,
		timedOut)
}
コード例 #7
0
ファイル: helpers.go プロジェクト: goframework/gf
// requestToken returns the issued token (pad + masked token) from the HTTP POST
// body or HTTP header. It will return nil if the token fails to decode.
func (cs *CsrfProtection) RequestToken(r *http.Request) []byte {
	// 1. Check the HTTP header first.
	issued := r.Header.Get(cs.Opts.RequestHeader)

	// 2. Fall back to the POST (form) value.
	if issued == "" {
		issued = r.PostFormValue(cs.Opts.FieldName)
	}

	// 3. Finally, fall back to the multipart form (if set).
	if issued == "" && r.MultipartForm != nil {
		vals := r.MultipartForm.Value[cs.Opts.FieldName]

		if len(vals) > 0 {
			issued = vals[0]
		}
	}

	// Decode the "issued" (pad + masked) token sent in the request. Return a
	// nil byte slice on a decoding error (this will fail upstream).
	decoded, err := base64.StdEncoding.DecodeString(issued)
	if err != nil {
		return nil
	}

	return decoded
}
コード例 #8
0
// PingSessionHandler ...
func PingSessionHandler(w http.ResponseWriter, r *http.Request, c *Context) {
	sessionIdHex := r.PostFormValue("session_id")
	machineId := r.PostFormValue("machine_id")
	if len(r.PostForm) != 2 || sessionIdHex == "" || machineId == "" {
		http.Error(w, "Retry with POST parameters: session_id, machine_id", http.StatusBadRequest)
		return
	}
	if !bson.IsObjectIdHex(sessionIdHex) {
		http.Error(w, fmt.Sprintf("Invalid session id %s", sessionIdHex), http.StatusBadRequest)
		return
	}
	sessionId := bson.ObjectIdHex(sessionIdHex)
	err := c.Store.PingSession(&Session{Id: sessionId, MachineId: machineId})
	switch err {
	case nil:
		fmt.Fprintln(w, sessionIdHex)
	case mgo.ErrNotFound:
		http.Error(w, fmt.Sprintf("Session %s does not exist or is already closed", sessionIdHex),
			http.StatusBadRequest)
	default:
		http.Error(w, fmt.Sprintf("Failed to ping session %s", sessionIdHex),
			http.StatusInternalServerError)
		log.Println(err)
	}
}
コード例 #9
0
ファイル: mock_scheduler.go プロジェクト: vj291284/test
func handleStop(w http.ResponseWriter, r *http.Request) error {
	r.ParseForm()

	stpRecid := r.PostFormValue("RecordingID")

	reqData := getstopPayload(stpRecid)
	httpStatus, err, _ := postRecord(reqData, r)

	if err != nil {
		log.Printf("Failed on send Record request! err:%v\n", err)

	}
	if httpStatus == 204 {
		log.Printf("Stop request Submitted Sucessfully to RM")
		for i := 0; i < upCount; i++ {
			updtEntries := updtDataGlb[i].Entries

			for j := range updtEntries {
				if updtEntries[j].RecordingID == stpRecid && updtEntries[j].Status == "COMPLETE" {
					updtEntries[j].Status = "STOPPED"

				}
			}
		}

	} else if httpStatus == 500 {
		log.Printf("RM not available please retry, ERROR: " + strconv.Itoa(httpStatus))

	}

	return nil

}
コード例 #10
0
func GetFeedbackByAdmin(w http.ResponseWriter, r *http.Request, userId string, userType models.UserType) interface{} {
	reservationId := r.PostFormValue("reservation_id")

	var result = map[string]interface{}{"state": "SUCCESS"}
	var al = buslogic.AdminLogic{}

	var feedback = make(map[string]interface{})
	reservation, err := al.GetFeedbackByAdmin(reservationId, userId, userType)
	if err != nil {
		ErrorHandler(w, r, err)
		return nil
	}
	if len(reservation.TeacherFeedback.TeacherFullname) == 0 {
		feedback["teacher_fullname"] = reservation.TeacherFullname
	} else {
		feedback["teacher_fullname"] = reservation.TeacherFeedback.TeacherFullname
	}
	if len(reservation.TeacherFeedback.TeacherUsername) == 0 {
		feedback["teacher_username"] = reservation.TeacherUsername
	} else {
		feedback["teacher_username"] = reservation.TeacherFeedback.TeacherUsername
	}
	if len(reservation.TeacherFeedback.StudentFullname) == 0 {
		feedback["student_fullname"] = reservation.StudentInfo.Name
	} else {
		feedback["student_fullname"] = reservation.TeacherFeedback.StudentFullname
	}
	feedback["problem"] = reservation.TeacherFeedback.Problem
	feedback["solution"] = reservation.TeacherFeedback.Solution
	feedback["advice"] = reservation.TeacherFeedback.AdviceToCenter
	result["feedback"] = feedback

	return result
}
コード例 #11
0
func GetStudentInfoByAdmin(w http.ResponseWriter, r *http.Request, userId string, userType models.UserType) interface{} {
	reservationId := r.PostFormValue("reservation_id")

	var result = map[string]interface{}{"state": "SUCCESS"}
	var al = buslogic.AdminLogic{}

	var studentJson = make(map[string]interface{})
	studentInfo, err := al.GetStudentInfoByAdmin(reservationId, userId, userType)
	if err != nil {
		ErrorHandler(w, r, err)
		return nil
	}
	studentJson["name"] = studentInfo.Name
	studentJson["gender"] = studentInfo.Gender
	studentJson["student_id"] = studentInfo.StudentId
	studentJson["school"] = studentInfo.School
	studentJson["hometown"] = studentInfo.Hometown
	studentJson["mobile"] = studentInfo.Mobile
	studentJson["email"] = studentInfo.Email
	studentJson["experience"] = studentInfo.Experience
	studentJson["problem"] = studentInfo.Problem
	result["student_info"] = studentJson

	return result
}
コード例 #12
0
func EditReservationByAdmin(w http.ResponseWriter, r *http.Request, userId string, userType models.UserType) interface{} {
	reservationId := r.PostFormValue("reservation_id")
	startTime := r.PostFormValue("start_time")
	endTime := r.PostFormValue("end_time")
	teacherUsername := r.PostFormValue("teacher_username")
	teacherFullname := r.PostFormValue("teacher_fullname")
	teacherMobile := r.PostFormValue("teacher_mobile")

	var result = map[string]interface{}{"state": "SUCCESS"}
	var al = buslogic.AdminLogic{}

	var reservationJson = make(map[string]interface{})
	reservation, err := al.EditReservationByAdmin(reservationId, startTime, endTime, teacherUsername,
		teacherFullname, teacherMobile, userId, userType)
	if err != nil {
		ErrorHandler(w, r, err)
		return nil
	}
	reservationJson["reservation_id"] = reservation.Id
	reservationJson["start_time"] = reservation.StartTime.In(utils.Location).Format(utils.TIME_PATTERN)
	reservationJson["end_time"] = reservation.EndTime.In(utils.Location).Format(utils.TIME_PATTERN)
	reservationJson["teacher_username"] = reservation.TeacherUsername
	reservationJson["teacher_fullname"] = reservation.TeacherFullname
	reservationJson["teacher_mobile"] = reservation.TeacherMobile
	result["reservation"] = reservationJson

	return result
}
コード例 #13
0
ファイル: route_thread.go プロジェクト: dominicwong617/gwp
// POST /thread/post
// Create the post
func postThread(writer http.ResponseWriter, request *http.Request) {
	sess, err := session(writer, request)
	if err != nil {
		http.Redirect(writer, request, "/login", 302)
	} else {
		err = request.ParseForm()
		if err != nil {
			danger(err, "Cannot parse form")
		}
		user, err := sess.User()
		if err != nil {
			danger(err, "Cannot get user from session")
		}
		body := request.PostFormValue("body")
		uuid := request.PostFormValue("uuid")
		thread, err := data.ThreadByUUID(uuid)
		if err != nil {
			error_message(writer, request, "Cannot read thread")
		}
		if _, err := user.CreatePost(thread, body); err != nil {
			danger(err, "Cannot create post")
		}
		url := fmt.Sprint("/thread/read?id=", uuid)
		http.Redirect(writer, request, url, 302)
	}
}
コード例 #14
0
ファイル: reading.go プロジェクト: bluefchen/studygolang
// /admin/reading/publish
func PublishReadingHandler(rw http.ResponseWriter, req *http.Request) {
	var data = make(map[string]interface{})

	if req.PostFormValue("submit") == "1" {
		user, _ := filter.CurrentUser(req)

		errMsg, err := service.SaveReading(req.PostForm, user["username"].(string))
		if err != nil {
			data["ok"] = 0
			data["error"] = errMsg
		} else {
			data["ok"] = 1
			data["msg"] = "操作成功"
		}
	} else {
		id, err := strconv.Atoi(req.FormValue("id"))
		if err == nil && id != 0 {
			data["reading"], err = service.FindReadingById(id)

			if err != nil {
				rw.WriteHeader(http.StatusInternalServerError)
				return
			}
		}

		// 设置内容模板
		req.Form.Set(filter.CONTENT_TPL_KEY, "/template/admin/reading/modify.html")
	}

	filter.SetData(req, data)
}
コード例 #15
0
ファイル: service_provider.go プロジェクト: iserko/empire
// Parse parses the SAMLResponse
func (sp *ServiceProvider) Parse(w http.ResponseWriter, r *http.Request) (*Assertion, error) {
	allowIdPInitiated := ""
	possibleRequestIDs := []string{allowIdPInitiated}

	// Find the request id that relates to this RelayState.
	relayState := r.PostFormValue("RelayState")
	if sp.cookieSecret() != nil && relayState != "" {
		cookieName := fmt.Sprintf("saml_%s", relayState)
		cookie, err := r.Cookie(cookieName)
		if err != nil {
			return nil, fmt.Errorf("cannot find %s cookie", cookieName)
		}

		// Verify the integrity of the cookie.
		state, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) {
			return sp.cookieSecret(), nil
		})
		if err != nil || !state.Valid {
			return nil, fmt.Errorf("could not decode state JWT: %v", err)
		}

		claims := state.Claims.(jwt.MapClaims)
		id := claims["id"].(string)

		possibleRequestIDs = append(possibleRequestIDs, id)

		// delete the cookie
		cookie.Value = ""
		cookie.Expires = time.Time{}
		http.SetCookie(w, cookie)
	}

	samlResponse := r.PostFormValue("SAMLResponse")
	return sp.ParseSAMLResponse(samlResponse, possibleRequestIDs)
}
コード例 #16
0
ファイル: jsonp.go プロジェクト: wavded/sockjs-go
func (h *handler) jsonpSend(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	var data io.Reader
	data = req.Body

	formReader := strings.NewReader(req.PostFormValue("d"))
	if formReader.Len() != 0 {
		data = formReader
	}
	if data == nil {
		http.Error(rw, "Payload expected.", http.StatusInternalServerError)
		return
	}
	var messages []string
	err := json.NewDecoder(data).Decode(&messages)
	if err == io.EOF {
		http.Error(rw, "Payload expected.", http.StatusInternalServerError)
		return
	}
	if err != nil {
		http.Error(rw, "Broken JSON encoding.", http.StatusInternalServerError)
		return
	}
	sessionID, _ := h.parseSessionID(req.URL)
	if sess, ok := h.sessions[sessionID]; !ok {
		http.NotFound(rw, req)
	} else {
		_ = sess.accept(messages...) // TODO(igm) reponse with http.StatusInternalServerError in case of err?
		rw.Header().Set("content-type", "text/plain; charset=UTF-8")
		rw.Write([]byte("ok"))
	}
}
コード例 #17
0
ファイル: stripe_example.go プロジェクト: qorio/omni
// stripeToken represents a valid card token returned by the Stripe API.
// We use this to create a charge against the card instead of directly handling
// the credit card details in our application. Note that you could potentially
// collect the expiry date to allow you to remind users to update their card
// details as it nears expiry.
func paymentHandler(w http.ResponseWriter, r *http.Request) {

	// Use stripe.SetKeyEnv() to read the STRIPE_API_KEY environmental variable or alternatively
	// use stripe.SetKey() to set it directly (just don't publish it to GitHub!)
	err := stripe.SetKeyEnv()

	if err != nil {
		log.Fatal(err)
	}

	params := stripe.ChargeParams{
		Desc: "Pastrami on Rye",
		// Amount as an integer: 2000 = $20.00
		Amount:   2000,
		Currency: "AUD",
		Token:    r.PostFormValue("stripeToken"),
	}

	_, err = stripe.Charges.Create(&params)

	if err == nil {
		fmt.Fprintf(w, "Successful test payment!")
	} else {
		fmt.Fprintf(w, "Unsuccessful test payment: "+err.Error())
	}

}
コード例 #18
0
func handleUpdate(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var (
		d   int
		day time.Weekday
		err error
	)
	// Check if there is a signed in user.
	u := currentUser(r)
	if u == nil {
		aelog.Errorf(c, "No signed in user for updating")
		goto out
	}
	// Validate XSRF token first.
	if !xsrftoken.Valid(r.PostFormValue(xsrfTokenName), xsrfKey, u.ID, updateURL) {
		aelog.Errorf(c, "XSRF token validation failed")
		goto out
	}
	// Extract the new favorite weekday.
	d, err = strconv.Atoi(r.PostFormValue(favoriteName))
	if err != nil {
		aelog.Errorf(c, "Failed to extract new favoriate weekday: %s", err)
		goto out
	}
	day = time.Weekday(d)
	if day < time.Sunday || day > time.Saturday {
		aelog.Errorf(c, "Got wrong value for favorite weekday: %d", d)
	}
	// Update the favorite weekday.
	updateWeekdayForUser(r, u, day)
out:
	// Redirect to home page to show the update result.
	http.Redirect(w, r, homeURL, http.StatusFound)
}
コード例 #19
0
ファイル: saml.go プロジェクト: tsuru/tsuru
// title: saml callback
// path: /auth/saml
// method: POST
// responses:
//   200: Ok
//   400: Invalid data
func samlCallbackLogin(w http.ResponseWriter, r *http.Request) error {
	if app.AuthScheme.Name() != "saml" {
		return &errors.HTTP{
			Code:    http.StatusBadRequest,
			Message: "This URL is only supported with saml enabled",
		}
	}
	params := map[string]string{}
	content := r.PostFormValue("SAMLResponse")
	if content == "" {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: "Empty SAML Response"}
	}
	params["callback"] = "true"
	params["xml"] = content
	//Get saml.SAMLAuthScheme, error already treated on first check
	scheme, _ := auth.GetScheme("saml")
	_, err := scheme.Login(params)
	if err != nil {
		msg := fmt.Sprintf(cmd.SamlCallbackFailureMessage(), err.Error())
		fmt.Fprintf(w, msg)
	} else {
		fmt.Fprintf(w, cmd.SamlCallbackSuccessMessage())
	}
	return nil
}
コード例 #20
0
ファイル: main.go プロジェクト: janit/http2status
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	tHeader.Execute(w, nil)

	tForm.Execute(w, map[string]interface{}{
		csrf.TemplateTag: csrf.TemplateField(r),
	})

	//url := r.URL.Query().Get("url")
	url := r.PostFormValue("url")

	if url != "" {

		obj := map[string]interface{}{}

		isH2, res, sanitizedUrl, err := Http2Status(url)
		if err != nil {
			obj["err"] = err
		} else {
			if !isH2 {
				obj["status"] = "Nope. It's not 1984 anymore, time to upgrade to http2."
			} else {
				obj["status"] = "You're on HTTP2!"
			}
		}

		obj["response"] = res
		obj["siteUrl"] = sanitizedUrl

		tResult.Execute(w, obj)
	}

	tFooter.Execute(w, nil)
}
コード例 #21
0
ファイル: server.go プロジェクト: vpetrov/icognition
func debugHandler(w http.ResponseWriter, r *http.Request) {
	var (
		err        error
		debug_info *DebugInfo
	)

	debug := r.PostFormValue("debug")

	if len(debug) == 0 {
		http.Error(w, "No debug information received.", http.StatusBadRequest)
		return
	}

	debug_info = &DebugInfo{}

	err = json.Unmarshal([]byte(debug), debug_info)
	if err != nil {
		http.Error(w, "Invalid debug information.", http.StatusBadRequest)
		return
	}

	//set current time
	debug_info.ReceivedAt = time.Now()
	debug_info.UserAgent = r.UserAgent()

	err = debug_collection.Insert(debug_info)
	if err != nil {
		log.Println(err)
	}

	//No need to return any content
	http.Error(w, "No content", http.StatusNoContent)
}
コード例 #22
0
ファイル: handler.go プロジェクト: NovemberFoxtrot/magnet
// LoginPostHandler writes out login response
func LoginPostHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, cfg *Config, connection *Connection) {
	username := req.PostFormValue("username")
	password := cryptPassword(req.PostFormValue("password"), cfg.SecretKey)

	var response []interface{}

	response, err := connection.LoginPost(username, password)

	if err != nil || len(response) == 0 {
		WriteJSONResponse(200, true, "Invalid username or password.", req, w)
	} else {
		// Store session
		userID := response[0].(map[string]interface{})["id"].(string)
		session := Session{UserID: userID,
			Expires: time.Now().Unix() + int64(cfg.SessionExpires)}

		response, err := connection.LoginPostInsertSession(session)

		if err != nil || response.Inserted < 1 {
			WriteJSONResponse(200, true, "Error creating the user session.", req, w)
		} else {
			session, _ := cs.Get(req, "magnet_session")
			session.Values["session_id"] = response.GeneratedKeys[0]
			session.Values["username"] = username
			session.Values["user_id"] = userID
			session.Save(req, w)
			WriteJSONResponse(200, false, "User correctly logged in.", req, w)
		}
	}
}
コード例 #23
0
ファイル: project.go プロジェクト: bluefchen/studygolang
// 更新状态
// uri: /admin/community/project/update_status
func UpdateProjectStatusHandler(rw http.ResponseWriter, req *http.Request) {
	id, err := strconv.Atoi(req.PostFormValue("id"))
	if err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		return
	}

	status, err := strconv.Atoi(req.FormValue("status"))
	if err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		return
	}

	var data = make(map[string]interface{})

	user, _ := filter.CurrentUser(req)

	err = service.UpdateProjectStatus(id, status, user["username"].(string))
	if err != nil {
		logger.Errorln("UpdateProjectStatusHandler error:", err)
		data["ok"] = 0
		data["error"] = "更新状态失败"
	} else {
		data["ok"] = 1
		data["msg"] = "更新状态成功"
	}

	filter.SetData(req, data)
}
コード例 #24
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)
	}
}
コード例 #25
0
ファイル: recaptcha.go プロジェクト: escribano/recaptcha
// Verify method, verifies if current request have valid re-captcha response and returns true or false
// This method also records any errors in validation.
// These errors can be received by calling LastError() method.
func (r *R) Verify(req http.Request) bool {
	r.lastError = make([]string, 1)
	response := req.PostFormValue("g-recaptcha-response")
	client := &http.Client{Timeout: 20 * time.Second}
	resp, err := client.PostForm(postUrl,
		url.Values{"secret": {r.Secret}, "response": {response}})
	if err != nil {
		r.lastError = append(r.lastError, err.Error())
		return false
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		r.lastError = append(r.lastError, err.Error())
		return false
	} else {
		gr := new(googleResponse)
		err := json.Unmarshal(body, gr)
		if err != nil {
			r.lastError = append(r.lastError, err.Error())
			return false
		}
		if !gr.Success {
			r.lastError = append(r.lastError, gr.ErrorCodes...)
		}
		return gr.Success
	}
}
コード例 #26
0
ファイル: main.go プロジェクト: beauhoyt/go-micro-services
func (s traceServer) requestHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		r.ParseForm()

		traceID := r.PostFormValue("traceId")
		if traceID == "" {
			http.Error(w, "Param traceId required", http.StatusBadRequest)
			return
		}

		msg := r.PostFormValue("msg")
		if msg == "" {
			http.Error(w, "Param msg required", http.StatusBadRequest)
			return
		}

		s.events[traceID] = append(s.events[traceID], msg)
	} else {
		traceID := r.URL.Query().Get("traceId")
		if traceID == "" {
			http.Error(w, "Param traceID required", http.StatusBadRequest)
			return
		}

		fmt.Fprintln(w, "<div class=wsd wsd_style=\"default\" ><pre>")
		for _, msg := range s.events[traceID] {
			fmt.Fprintln(w, msg)
		}
		fmt.Fprintln(w, "</pre></div>")
		fmt.Fprintln(w, "<script type=\"text/javascript\" src=\"http://www.websequencediagrams.com/service.js\"></script>")
	}
}
コード例 #27
0
ファイル: deploy.go プロジェクト: caputomarcos/tsuru
func deployRollback(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	appName := r.URL.Query().Get(":appname")
	instance, err := app.GetByName(appName)
	if err != nil {
		return &errors.HTTP{Code: http.StatusNotFound, Message: fmt.Sprintf("App %s not found.", appName)}
	}
	image := r.PostFormValue("image")
	if image == "" {
		return &errors.HTTP{
			Code:    http.StatusBadRequest,
			Message: "you cannot rollback without an image name",
		}
	}
	w.Header().Set("Content-Type", "application/json")
	keepAliveWriter := io.NewKeepAliveWriter(w, 30*time.Second, "")
	defer keepAliveWriter.Stop()
	writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
	if !regexp.MustCompile(":v[0-9]+$").MatchString(image) {
		img, err := getImage(appName, image)
		//err is not handled because it is treated in funcion app.Deploy()
		if err == nil {
			image = img
		}
	}
	err = app.Deploy(app.DeployOptions{
		App:          instance,
		OutputStream: writer,
		Image:        image,
		User:         t.GetUserName(),
	})
	if err != nil {
		writer.Encode(io.SimpleJsonMessage{Error: err.Error()})
	}
	return nil
}
コード例 #28
0
func ControllerAuthenticate(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	switch r.Method {
	case "GET":
	case "POST":
		_, err := r.Cookie("sid")

		if err != nil {
			user := r.PostFormValue("username")
			password := r.PostFormValue("password")
			expiration := time.Now().Add(365 * 24 * time.Hour)

			if authenticateUser(user, password) {
				cookie := http.Cookie{
					Name:    "sid",
					Value:   user + password,
					Expires: expiration}

				http.SetCookie(w, &cookie)
			}
		}

		http.Redirect(w, r, "/", http.StatusSeeOther)
	case "PUT":
	case "DELETE":
	default:
	}

}
コード例 #29
0
ファイル: pages.go プロジェクト: denisbakhtin/blog
//PageDelete handles /admin/delete_page route
func PageDelete(w http.ResponseWriter, r *http.Request) {
	tmpl := shared.Template(r)

	if r.Method == "POST" {

		page, err := models.GetPage(r.PostFormValue("id"))
		if err != nil {
			log.Printf("ERROR: %s\n", err)
			w.WriteHeader(404)
			tmpl.Lookup("errors/404").Execute(w, shared.ErrorData(err))
		}

		if err := page.Delete(); err != nil {
			log.Printf("ERROR: %s\n", err)
			w.WriteHeader(500)
			tmpl.Lookup("errors/500").Execute(w, shared.ErrorData(err))
			return
		}
		http.Redirect(w, r, "/admin/pages", 303)

	} else {
		err := fmt.Errorf("Method %q not allowed", r.Method)
		log.Printf("ERROR: %s\n", err)
		w.WriteHeader(405)
		tmpl.Lookup("errors/405").Execute(w, shared.ErrorData(err))
	}
}
コード例 #30
0
ファイル: sshkeys.go プロジェクト: Jitendrakry/ipxed
// CreateSSHKeyHandler creates a new sshkey.
func CreateSSHKeyHandler(w http.ResponseWriter, r *http.Request) {
	s := SSHKey{}
	s.Name = r.PostFormValue("name")
	s.Key = r.PostFormValue("sshkey")
	s.Save()
	http.Redirect(w, r, "/sshkeys/"+s.Name, http.StatusMovedPermanently)
}