本文整理匯總了Golang中github.com/gorilla/csrf.TemplateField函數的典型用法代碼示例。如果您正苦於以下問題:Golang TemplateField函數的具體用法?Golang TemplateField怎麽用?Golang TemplateField使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了TemplateField函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Add
// Add adds a new shorturl
func (view View) Add(w http.ResponseWriter, req *http.Request) {
url := req.FormValue("url")
if url == "" {
http.Redirect(w, req, "/", http.StatusFound)
return
}
host := getIP(req)
if err := checkAllowed(req, url, host); err != nil {
data := map[string]interface{}{
csrf.TemplateTag: csrf.TemplateField(req),
"Error": err,
}
view.renderTemplate(w, "index", data)
return
}
clientid := getClientID(req.Cookies())
if clientid == "" {
http.Error(w, "Failed to add shorturl", http.StatusForbidden)
return
}
s, err := Add(view.DB, url, host, clientid)
if err != nil {
log.Printf("Failed to add (%s)", err)
http.Error(w, "Failed to add short url", http.StatusInternalServerError)
return
}
http.Redirect(w, req, s.PreviewURL(), http.StatusFound)
}
示例2: newPost
func (controller *usersController) newPost(rw http.ResponseWriter, req *http.Request) (int, error) {
err := req.ParseForm()
if err != nil {
return http.StatusInternalServerError, err
}
decoder := schema.NewDecoder()
// Ignore unknown keys to prevent errors from the CSRF token.
decoder.IgnoreUnknownKeys(true)
formUser := new(viewmodels.UsersEditViewModel)
err = decoder.Decode(formUser, req.PostForm)
if err != nil {
return http.StatusInternalServerError, err
}
valErrors := validateUserForm(formUser, false)
if len(valErrors) > 0 {
isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
vm := viewmodels.NewUserViewModel(formUser, controller.roles, isAuthenticated, user, valErrors)
vm.CsrfField = csrf.TemplateField(req)
return http.StatusOK, controller.newTemplate.Execute(rw, vm)
}
var user httpauth.UserData
user.Username = formUser.Username
user.Email = formUser.Email
password := formUser.Password
user.Role = formUser.Role
err = controller.authorizer.Register(rw, req, user, password)
if err != nil {
return http.StatusInternalServerError, err
}
http.Redirect(rw, req, "/settings/users", http.StatusSeeOther)
return http.StatusSeeOther, nil
}
示例3: post
func (controller *profileController) post(rw http.ResponseWriter, req *http.Request) (int, error) {
err := req.ParseForm()
if err != nil {
return http.StatusInternalServerError, err
}
decoder := schema.NewDecoder()
// Ignore unknown keys to prevent errors from the CSRF token.
decoder.IgnoreUnknownKeys(true)
formUser := new(viewmodels.ProfileEditViewModel)
err = decoder.Decode(formUser, req.PostForm)
if err != nil {
return http.StatusInternalServerError, err
}
valErrors := validateProfileForm(formUser, true)
if len(valErrors) > 0 {
isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
vm := viewmodels.EditProfileViewModel(formUser, isAuthenticated, user, valErrors)
vm.CsrfField = csrf.TemplateField(req)
return http.StatusOK, controller.template.Execute(rw, vm)
}
// Update the user.
err = controller.authorizer.Update(rw, req, "", formUser.Password, formUser.Email)
if err != nil {
return http.StatusInternalServerError, err
}
http.Redirect(rw, req, "/", http.StatusSeeOther)
return http.StatusSeeOther, nil
}
示例4: loginHandler
func loginHandler(c *gin.Context) {
redirectTarget := strings.TrimSpace(c.DefaultPostForm("next", c.DefaultQuery("next", "")))
// c.HTML(http.StatusOK, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
// "err": "", "user_name": "", "pass": "", "next": redirectTarget})
renderTemplate(c.Writer, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
"err": "", "user_name": "", "pass": "", "next": redirectTarget})
}
示例5: editGet
func (controller *contactsController) editGet(rw http.ResponseWriter, req *http.Request) (int, error) {
vars := mux.Vars(req)
contactID, err := strconv.ParseInt(vars["contactID"], 10, 64)
if err != nil {
return http.StatusInternalServerError, err
}
// Get the contact to edit
contact := new(database.Contact)
err = contact.GetContact(controller.DB, contactID)
if err != nil {
return http.StatusInternalServerError, err
}
isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
contactEdit := new(viewmodels.ContactsEditViewModel)
contactEdit.Name = contact.Name
contactEdit.ContactID = contact.ContactID
contactEdit.EmailAddress = contact.EmailAddress
contactEdit.SmsNumber = contact.SmsNumber
contactEdit.EmailActive = contact.EmailActive
contactEdit.SmsActive = contact.SmsActive
contactEdit.SelectedSites, err = getContactSiteIDs(controller, contact)
if err != nil {
return http.StatusInternalServerError, err
}
sites, errGet := getAllSites(controller)
if errGet != nil {
return http.StatusInternalServerError, errGet
}
vm := viewmodels.EditContactViewModel(contactEdit, sites, isAuthenticated, user, make(map[string]string))
vm.CsrfField = csrf.TemplateField(req)
return http.StatusOK, controller.editTemplate.Execute(rw, vm)
}
示例6: upload
// upload logic
func upload(c *gin.Context) {
if c.Request.Method == "GET" {
ct := gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request)}
form := renderStrTemplate("uploadForm.html", ct)
renderTemplate(c.Writer, "base.html", updateMap(ct, map[string]interface{}{"title": "Upload", "pageTitle": "Upload Form", "content": form}))
} else if c.Request.Method == "POST" {
c.Request.ParseMultipartForm(32 << 20)
file, handler, err := c.Request.FormFile("uploadfile")
if err != nil {
log.Println(err)
c.Redirect(http.StatusFound, "/upload")
return
}
defer file.Close()
// fmt.Fprintf(c.Writer, "%v", handler.Header)
f, err := os.OpenFile("/tmp/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Println(err)
c.Redirect(http.StatusFound, "/upload")
return
}
defer f.Close()
io.Copy(f, file)
c.Redirect(http.StatusFound, "/upload")
}
}
示例7: SetUser
// SetUser is a HTTP middleware for setting the user and build information.
func SetUser(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
context.Set(req, csrf.TemplateTag, csrf.TemplateField(req)) // Set CSRF field everywhere
context.Set(req, "Version", Version)
context.Set(req, "Branch", Branch)
context.Set(req, "user", &Account{})
ses, err := store.Get(req, "evemu")
if err != nil {
log.Printf("Failed to get session cookie: %s", err.Error())
h.ServeHTTP(rw, req)
return
}
if v, ok := ses.Values["user"]; ok {
if v.(int) == 0 {
h.ServeHTTP(rw, req)
return
}
//a, err := DBAccountFromID(v.(int))
a, err := Layer.GetAccountFromID(v.(int)) // TODO: Unsafe, may panic
if err != nil {
log.Printf("Failed to get account from id: %s", err.Error())
h.ServeHTTP(rw, req)
return
}
context.Set(req, "user", a)
}
h.ServeHTTP(rw, req)
})
}
示例8: newGet
func (controller *usersController) newGet(rw http.ResponseWriter, req *http.Request) (int, error) {
isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
userEdit := new(viewmodels.UsersEditViewModel)
userEdit.Role = "user"
vm := viewmodels.NewUserViewModel(userEdit, controller.roles, isAuthenticated, user, make(map[string]string))
vm.CsrfField = csrf.TemplateField(req)
return http.StatusOK, controller.newTemplate.Execute(rw, vm)
}
示例9: writeTemplateParam
func (self httpModUI) writeTemplateParam(wr http.ResponseWriter, r *http.Request, name string, param map[string]interface{}) {
if param == nil {
param = make(map[string]interface{})
}
param[csrf.TemplateTag] = csrf.TemplateField(r)
param["prefix"] = self.prefix
param["mod_prefix"] = self.mod_prefix
io.WriteString(wr, template.renderTemplate(name, param))
}
示例10: DefaultData
//DefaultData returns common to all pages template data
func DefaultData(r *http.Request) map[string]interface{} {
return map[string]interface{}{
"ActiveUser": context.Get(r, "user"), //signed in models.User
"Active": "", //active uri shortening for menu item highlight
"Title": "", //page title:w
"SignupEnabled": context.Get(r, "signup_enabled"), //signup route is enabled (otherwise everyone can signup ;)
csrf.TemplateTag: csrf.TemplateField(r),
}
}
示例11: getSignup
func getSignup(ctx context, w http.ResponseWriter, req *http.Request) {
wrap := map[string]interface{}{
"Stylesheets": assets.StylesheetHandlers,
"Scripts": assets.ScriptHandlers,
csrf.TemplateTag: csrf.TemplateField(req),
}
if err := assets.Templates["signup.html"].Execute(w, wrap); err != nil {
log.Println(err)
http.Error(w, err500, 500)
return
}
}
示例12: newPost
func (controller *contactsController) newPost(rw http.ResponseWriter, req *http.Request) (int, error) {
err := req.ParseForm()
if err != nil {
return http.StatusInternalServerError, err
}
decoder := schema.NewDecoder()
// Ignore unknown keys to prevent errors from the CSRF token.
decoder.IgnoreUnknownKeys(true)
formContact := new(viewmodels.ContactsEditViewModel)
err = decoder.Decode(formContact, req.PostForm)
if err != nil {
return http.StatusInternalServerError, err
}
valErrors := validateContactForm(formContact)
if len(valErrors) > 0 {
isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
sites, errGet := getAllSites(controller)
if errGet != nil {
return http.StatusInternalServerError, err
}
vm := viewmodels.NewContactViewModel(formContact, sites, false,
isAuthenticated, user, valErrors)
vm.CsrfField = csrf.TemplateField(req)
return http.StatusOK, controller.newTemplate.Execute(rw, vm)
}
contact := database.Contact{}
mapContacts(&contact, formContact)
err = contact.CreateContact(controller.DB)
if err != nil {
return http.StatusInternalServerError, err
}
//Add contact to any selected sites
for _, siteSelID := range formContact.SelectedSites {
err = addContactToSite(controller, contact.ContactID, siteSelID)
if err != nil {
return http.StatusInternalServerError, err
}
}
// Refresh the pinger with the changes.
// TODO: Check whether this contact has been added to any site first.
err = controller.pinger.UpdateSiteSettings()
if err != nil {
return http.StatusInternalServerError, err
}
http.Redirect(rw, req, "/settings/contacts", http.StatusSeeOther)
return http.StatusSeeOther, nil
}
示例13: pageRouter
func pageRouter(c *gin.Context) {
var db = connectDB()
defer db.Close()
page, err := getPage(db, c.Param("link"))
ctxt := gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
"title": page.Title_ru, "pageTitle": page.Title_ru, "content": page.Content_ru}
if err != nil {
writeError(c, "<b>Извините, но страница не найдена</b>", http.StatusNotFound)
return
}
renderTemplate(c.Writer, "base.html", ctxt)
}
示例14: newPost
func (controller *sitesController) newPost(rw http.ResponseWriter, req *http.Request) (int, error) {
err := req.ParseForm()
if err != nil {
return http.StatusInternalServerError, err
}
decoder := schema.NewDecoder()
// Ignore unknown keys to prevent errors from the CSRF token.
decoder.IgnoreUnknownKeys(true)
formSite := new(viewmodels.SitesEditViewModel)
err = decoder.Decode(formSite, req.PostForm)
if err != nil {
return http.StatusInternalServerError, err
}
valErrors := validateSiteForm(formSite)
if len(valErrors) > 0 {
isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
var contacts database.Contacts
err = contacts.GetContacts(controller.DB)
if err != nil {
return http.StatusInternalServerError, err
}
vm := viewmodels.NewSiteViewModel(formSite, contacts, isAuthenticated, user, valErrors)
vm.CsrfField = csrf.TemplateField(req)
return http.StatusOK, controller.newTemplate.Execute(rw, vm)
}
site := database.Site{}
viewmodels.MapSiteVMtoDB(formSite, &site)
err = site.CreateSite(controller.DB)
if err != nil {
return http.StatusInternalServerError, err
}
//Add any selected contacts
for _, contactSelID := range formSite.SelectedContacts {
err = site.AddContactToSite(controller.DB, contactSelID)
if err != nil {
return http.StatusInternalServerError, err
}
}
// Refresh the pinger with the changes.
err = controller.pinger.UpdateSiteSettings()
if err != nil {
return http.StatusInternalServerError, err
}
http.Redirect(rw, req, "/settings", http.StatusSeeOther)
return http.StatusSeeOther, nil
}
示例15: getLogin
func getLogin(ctx context, w http.ResponseWriter, req *http.Request) {
wrap := struct {
Stylesheets map[string]http.Handler
Scripts map[string]http.Handler
CSRFField template.HTML
BadAuth bool // The previous request was a failed login attempt
}{assets.StylesheetHandlers, assets.ScriptHandlers, csrf.TemplateField(req), ctx.badAuth}
if err := assets.Templates["login.html"].Execute(w, wrap); err != nil {
log.Println(err)
http.Error(w, err500, 500)
return
}
}