本文整理汇总了Golang中net/http.Request.PostFormValue方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.PostFormValue方法的具体用法?Golang Request.PostFormValue怎么用?Golang Request.PostFormValue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Request
的用法示例。
在下文中一共展示了Request.PostFormValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ModifyRuleHandler
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: notificationHandler
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: postRegister
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: FieldPostHandler
// 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: viewInvite
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: compile
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: RequestToken
// 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: PingSessionHandler
// 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: handleStop
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: GetFeedbackByAdmin
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: GetStudentInfoByAdmin
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: EditReservationByAdmin
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: postThread
// 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: PublishReadingHandler
// /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: Parse
// 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)
}