Example #1
0
func (w *RadioWidget) Radios(attrs []string, checkedValue string) []template.HTML {
	id, _ := w.Attrs().Get("id")
	radios := make([]template.HTML, 0, len(w.choices))
	for i, choice := range w.choices {
		wAttrs := w.Attrs().Clone()
		wAttrs.Set("id", fmt.Sprintf("%v_%v", id, i))
		wAttrs.FromSlice(attrs)

		value := tTemplate.HTMLEscapeString(choice[0])
		label := tTemplate.HTMLEscapeString(choice[1])

		checked := ""
		if value == checkedValue {
			checked = ` checked="checked"`
		}

		radio := fmt.Sprintf(
			`<input%v value="%v"%v /> %v`,
			wAttrs.String(),
			value,
			checked,
			label)
		radios = append(radios, template.HTML(radio))
	}
	return radios
}
Example #2
0
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) //get request method
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, token)
	} else {
		// log in request
		r.ParseForm()
		token := r.Form.Get("token")
		if token != "" {
			fmt.Println("Token: ", token)
			// check token validity
		} else {
			// give error if no token
		}
		fmt.Println("username length:", len(r.Form["username"][0]))
		fmt.Println("username:"******"username"))) // print in server side
		fmt.Println("password:"******"password")))
		template.HTMLEscape(w, []byte(r.Form.Get("username"))) // respond to client
	}
}
Example #3
0
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) //获取请求的方法
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, token)
	} else {
		//请求的是登陆数据,那么执行登陆的逻辑判断
		r.ParseForm()
		token := r.Form.Get("token")
		fmt.Println(token)
		if token != "" {

			fmt.Println("***************************")
			//验证token的合法性
		} else {
			fmt.Println("============================")
			//不存在token报错
		}
		fmt.Println("username length:", len(r.Form["username"][0]))
		fmt.Println("username:"******"username"))) //输出到服务器端
		fmt.Println("password:"******"password")))
		template.HTMLEscape(w, []byte(r.Form.Get("username"))) //输出到客户端
	}
}
func (a *FragmentFormatterEx) Format(f *highlight.Fragment, orderedTermLocations highlight.TermLocations) string {
	rv := ""
	curr := f.Start
	for _, termLocation := range orderedTermLocations {
		if termLocation == nil {
			continue
		}
		if termLocation.Start < curr {
			continue
		}
		if termLocation.End > f.End {
			break
		}
		// add the stuff before this location
		rv += tt.HTMLEscapeString(string(f.Orig[curr:termLocation.Start]))
		// add the color
		rv += a.before
		// add the term itself
		rv += tt.HTMLEscapeString(string(f.Orig[termLocation.Start:termLocation.End]))
		// reset the color
		rv += a.after
		// update current
		curr = termLocation.End
	}
	// add any remaining text after the last token
	rv += tt.HTMLEscapeString(string(f.Orig[curr:f.End]))

	return rv
}
Example #5
0
func handleSign(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		serve404(w)
		return
	}
	c := appengine.NewContext(r)
	u := user.Current(c)
	userName := ""
	if u != nil { //a google user
		userName = u.String()
	} else { //not a google user
		//is it a local user?
		cookie, err := r.Cookie("email")
		if err == nil {
			userName = cookie.Value
		} else { //no logged in yet

			badRequest(w, "Only login user can post messages.")
			return
		}
	}
	if err := r.ParseForm(); err != nil {
		serveError(c, w, err)
		return
	}
	tagsString := r.FormValue("tags")
	m := &Message{
		ID:      0,
		Title:   template.HTMLEscapeString(r.FormValue("title")),
		Author:  template.HTMLEscapeString(r.FormValue("author")),
		Content: []byte(template.HTMLEscapeString(r.FormValue("content"))),
		Tags:    strings.Split(template.HTMLEscapeString(tagsString), ","),
		Date:    time.Now(),
		Views:   0,
		Good:    0,
		Bad:     0,
	}
	if badTitle(m.Title) || badAuthor(m.Author) || badContent(string(m.Content)) || badTag(tagsString) {
		badRequest(w, "Input too long")
		return
	}

	processMsgContent(m)
	//TODO: build References and Referedby list
	if u := user.Current(c); u != nil {
		m.Author = userName
		//TODO: hook this message under user's msglist
	}
	k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "aMessage", nil), m)
	if err != nil {
		serveError(c, w, err)
		return
	}
	putMsgTags(r, k.IntID(), m.Tags)
	setCount(w, r)
	http.Redirect(w, r, "/", http.StatusFound)
}
Example #6
0
func Compute(uc *understand.Circuit) *Circuit {
	c := &Circuit{Name: uc.Name()}

	// Peers
	var z float64 // Total weight
	var i int
	inv := make(map[*understand.Peer]int)
	for _, p := range uc.Peer {
		inv[p] = i
		// weight := float64(len(p.Valve))
		z += 1
		c.Peer = append(c.Peer,
			&Peer{
				ID:     fmt.Sprintf("peer-%s", p.Name),
				Name:   template.HTMLEscapeString(fmt.Sprintf("%v", p.Name)),
				Design: template.HTMLEscapeString(fmt.Sprintf("%v", p.Design)),
				Weight: 1, //weight,
			},
		)
		i++
	}
	var u float64
	const MaxRadius = 0.9
	for _, p := range c.Peer {
		p.Angle = 2 * math.Pi * (u + p.Weight/2) / z
		p.Anchor = CirclePointOfAngle(p.Angle)
		p.Radius = MaxRadius * p.Weight / z
		u += p.Weight
	}

	// Matchings
	for _, p := range uc.Peer { // From
		pp := c.Peer[inv[p]]
		for _, v := range p.Valve { // To
			qq := c.Peer[inv[v.Matching.Of]]
			x := pp.Anchor
			y := qq.Anchor
			c.Match = append(c.Match,
				&Match{
					ID:          fmt.Sprintf("match-%s-%s", pp.Name, v.Name),
					FromAnchor:  x,
					ToAnchor:    y,
					FromTangent: Scalar(0.5, x),
					ToTangent:   Scalar(0.5, y),
					Valve:       v.Name,
				},
			)
		}
	}
	return c
}
Example #7
0
func directiveInsertWordBreaks(value data.Value, args []data.Value) data.Value {
	var (
		input    = template.HTMLEscapeString(value.String())
		maxChars = int(args[0].(data.Int))
		chars    = 0
		output   *bytes.Buffer // create the buffer lazily
	)
	for i, ch := range input {
		switch {
		case ch == ' ':
			chars = 0
		case chars >= maxChars:
			if output == nil {
				output = bytes.NewBufferString(input[:i])
			}
			output.WriteString("<wbr>")
			chars = 1
		default:
			chars++
		}
		if output != nil {
			output.WriteRune(ch)
		}
	}
	if output == nil {
		return value
	}
	return data.String(output.String())
}
Example #8
0
func (w *SelectWidget) Options(selValues ...string) []string {
	options := make([]string, 0, len(w.choices))
	for _, choice := range w.choices {
		value := tTemplate.HTMLEscapeString(choice[0])
		label := tTemplate.HTMLEscapeString(choice[1])
		attrs := ""
		for _, selValue := range selValues {
			if value == selValue {
				attrs = ` selected="selected"`
			}
		}
		option := fmt.Sprintf(`<option value="%v"%v>%v</option>`, value, attrs, label)
		options = append(options, option)
	}
	return options
}
Example #9
0
func (disp_handler DispHandler) parse_input(r *http.Request) (locate_id uint32, err error) {

	//先解析获取数据
	err = r.ParseForm()

	if err != nil {
		return
	}

	locate_id = 0
	var tmp uint64 = 0

	str_locate_id, ok := r.Form["locate_id"]

	if ok == false {
		err = ErrorInputParameter
		return
	} else {
		tmp, err = strconv.ParseUint(template.HTMLEscapeString(str_locate_id[0]), 10, 32)
		if err != nil || tmp == 0 {
			err = ErrorInputParameter
			return
		} else {
			locate_id = uint32(tmp)
		}
	}

	err = nil
	return
}
Example #10
0
func code(file string, arg []interface{}) (string, error) {
	text := contents(file)
	var command string
	switch len(arg) {
	case 0:
		// whole file.
		command = fmt.Sprintf("code %q", file)
	case 1:
		// one line, specified by line or regexp.
		command = fmt.Sprintf("code %q %s", file, format(arg[0]))
		text = oneLine(file, text, arg[0])
	case 2:
		// multiple lines, specified by line or regexp.
		command = fmt.Sprintf("code %q %s %s", file, format(arg[0]), format(arg[1]))
		text = multipleLines(file, text, arg[0], arg[1])
	default:
		return "", fmt.Errorf("incorrect code invocation: code %q %v", file, arg)
	}
	// Replace tabs by spaces, which work better in HTML.
	text = strings.Replace(text, "\t", "    ", -1)
	// Escape the program text for HTML.
	if *html {
		text = template.HTMLEscapeString(text)
	}
	// Include the command as a comment.
	if *html {
		text = fmt.Sprintf("<!--{{%s}}\n-->%s", command, text)
	} else {
		text = fmt.Sprintf("// %s\n%s", command, text)
	}
	return text, nil
}
Example #11
0
func exampleIdFn(v interface{}, example *doc.Example) string {
	buf := make([]byte, 0, 64)
	buf = append(buf, "_example"...)

	switch v := v.(type) {
	case *doc.Type:
		buf = append(buf, '_')
		buf = append(buf, v.Name...)
	case *doc.Func:
		buf = append(buf, '_')
		if v.Recv != "" {
			if v.Recv[0] == '*' {
				buf = append(buf, v.Recv[1:]...)
			} else {
				buf = append(buf, v.Recv...)
			}
			buf = append(buf, '_')
		}
		buf = append(buf, v.Name...)
	}
	if example.Name != "" {
		buf = append(buf, '-')
		buf = append(buf, example.Name...)
	}
	return template.HTMLEscapeString(string(buf))
}
Example #12
0
func breadcrumbsFn(pdoc *doc.Package) string {
	if !strings.HasPrefix(pdoc.ImportPath, pdoc.ProjectRoot) {
		return ""
	}
	var buf bytes.Buffer
	i := 0
	j := len(pdoc.ProjectRoot)
	if j == 0 {
		buf.WriteString("<a href=\"/-/go\" title=\"Standard Packages\">☆</a> ")
		j = strings.IndexRune(pdoc.ImportPath, '/')
		if j < 0 {
			j = len(pdoc.ImportPath)
		}
	}
	for {
		buf.WriteString(`<a href="/`)
		buf.WriteString(urlFn(pdoc.ImportPath[:j]))
		buf.WriteString(`">`)
		buf.WriteString(template.HTMLEscapeString(pdoc.ImportPath[i:j]))
		buf.WriteString("</a>")
		i = j + 1
		if i >= len(pdoc.ImportPath) {
			break
		}
		buf.WriteByte('/')
		j = strings.IndexRune(pdoc.ImportPath[i:], '/')
		if j < 0 {
			j = len(pdoc.ImportPath)
		} else {
			j += i
		}
	}
	return buf.String()
}
Example #13
0
func code(file string, arg ...interface{}) (string, error) {
	text := contents(file)
	var command string
	switch len(arg) {
	case 0:
		// text is already whole file.
		command = fmt.Sprintf("code %q", file)
	case 1:
		command = fmt.Sprintf("code %q %s", file, format(arg[0]))
		text = oneLine(file, text, arg[0])
	case 2:
		command = fmt.Sprintf("code %q %s %s", file, format(arg[0]), format(arg[1]))
		text = multipleLines(file, text, arg[0], arg[1])
	default:
		return "", fmt.Errorf("incorrect code invocation: code %q %q", file, arg)
	}
	// Trim spaces from output.
	text = strings.Trim(text, "\n")
	// Replace tabs by spaces, which work better in HTML.
	text = strings.Replace(text, "\t", "    ", -1)
	// Escape the program text for HTML.
	text = template.HTMLEscapeString(text)
	// Include the command as a comment.
	text = fmt.Sprintf("<pre><!--{{%s}}\n-->%s</pre>", command, text)
	return text, nil
}
Example #14
0
func TestEscapge() {
	str := template.HTMLEscapeString("<br>hello</br>")
	fmt.Println(str)

	jsStr := template.JSEscapeString("<script>alert('123')</script>")
	fmt.Println(jsStr)
}
Example #15
0
// Process creates and sets the message that will be sent,
// and sends the message according to the mail adress
// its a helper method to send message
func (c *Controller) Process(m *Mail) error {
	if m.Properties == nil {
		m.Properties = NewProperties()
	}

	user := c.getUserInfo(m)

	m.SetOption("subject", m.Subject)

	// set default properties
	m.SetOption("env", c.env)
	m.SetOption("host", c.host)

	if m.Properties.Options["subject"] == keyInvitedCreateTeam {
		return c.mailgun.SendMailgunEmail(m)
	}

	event := &eventexporter.Event{
		Name: m.Subject,
		User: user,
		Body: &eventexporter.Body{
			Content: template.HTMLEscapeString(m.HTML),
		},
		Properties: m.Properties.Options,
	}
	return c.emailer.Send(event)
}
Example #16
0
// importPathFn formats an import with zero width space characters to allow for breaks.
func importPathFn(path string) string {
	path = template.HTMLEscapeString(path)
	if len(path) > 45 {
		// Allow long import paths to break following "/"
		path = strings.Replace(path, "/", "/&#8203;", -1)
	}
	return path
}
Example #17
0
func handleComment(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		serve404(w)
		return
	}
	c := appengine.NewContext(r)
	if err := r.ParseForm(); err != nil {
		serveError(c, w, err)
		return
	}
	m := &Comment{
		ID:      0,
		Author:  template.HTMLEscapeString(r.FormValue("newauthor")),
		Content: template.HTMLEscapeString(r.FormValue("content")),
		Date:    time.Now(),
		Good:    0,
		Bad:     0,
	}
	if badAuthor(m.Author) || badComment(m.Content) {
		badRequest(w, "Input too long!")
		return
	}
	processCmtContent(m)

	//TODO: build References and Referedby list
	if u := user.Current(c); u != nil {
		m.Author = u.String()
		//TODO: hook this message under user's msglist
	}
	k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "aComment", nil), m)
	if err != nil {
		serveError(c, w, err)
		return
	}

	msgid, err := strconv.ParseInt(r.FormValue("cmtid"), 0, 64)
	//
	msg := getMessage(r, msgid)
	msg.Comments = append(msg.Comments, k.IntID())
	putMessage(r, msgid, msg)
	http.Redirect(w, r, "/msg/?id="+strconv.FormatInt(msgid, 10), http.StatusFound)
}
Example #18
0
func (s *httpServer) serveSearchEntries(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	res, err := index.Search(r.Form["query"][0])
	if err != nil {
		http.Error(w, "Bad Request", http.StatusBadRequest)
		log.Warning(err)
		return
	}
	searchRes := make([]*SearchResult, 0, len(res.Hits))
	for _, hit := range res.Hits {
		entry := storage.LoadEntry(hit.ID)
		if entry != nil {
			title := template.HTML(tt.HTMLEscapeString(entry.Title))
			if thit, ok := hit.Fragments["Title"]; ok {
				title = template.HTML(thit[0])
			}

			searchHits, ok := hit.Fragments["Body"]
			result := &SearchResult{
				Id:    hit.ID,
				Title: title,
				Tags:  entry.Tags,
			}
			if ok {
				hitTexts := make([]template.HTML, 0, len(searchHits))
				for _, hitText := range searchHits {
					hitTexts = append(hitTexts, template.HTML(hitText))
				}
				result.Texts = hitTexts
			} else {
				result.Texts = []template.HTML{
					template.HTML(tt.HTMLEscapeString(entry.GetBodySnippet())),
				}
			}

			searchRes = append(searchRes, result)
		}
	}
	renderTemplate(w, "search_result", searchRes)
}
Example #19
0
func (node *ValNode) Render(ctx Context, w io.Writer) error {
	val, found := ctx.Get(node.name)
	if !found {
		return nil
		//return errors.New("key=" + node.name + " NOT Found")
	}
	str := val.String()
	//log.Println("ValNode --> " + str)
	if node.Escape {
		str = _g_tpl.HTMLEscapeString(str)
	}
	_, err := w.Write([]byte(str))
	return err
}
Example #20
0
func (w *WidgetAttrs) Set(name, value string) {
	value = tTemplate.HTMLEscapeString(value)

	exists := false
	for i := range w.attrs {
		attr := &w.attrs[i]
		if attr[0] == name {
			exists = true
			attr[1] = value
		}
	}
	if !exists {
		w.attrs = append(w.attrs, [...]string{name, value})
	}
}
Example #21
0
// formatCell formats number as an HTML table cell, with proper class depending on the val type.
func formatCell(tag, opts string, val interface{}, f string) string {
	var class string
	switch reflect.ValueOf(val).Kind() {
	case reflect.Int64, reflect.Int:
		class = "value-int"
	case reflect.Float64:
		class = "value-float"
	default:
		if _, ok := val.(time.Time); ok {
			class = "value-time"
		} else {
			class = "value-string"
		}
	}
	return fmt.Sprintf("<%s class='%s' %s>%s</%s>", tag, class, opts, template.HTMLEscapeString(format(val, f)), tag)
}
Example #22
0
func breadcrumbsFn(pdoc *doc.Package, page string) string {
	if !strings.HasPrefix(pdoc.ImportPath, pdoc.ProjectRoot) {
		return ""
	}
	var buf bytes.Buffer
	i := 0
	j := len(pdoc.ProjectRoot)
	if j == 0 {
		j = strings.IndexRune(pdoc.ImportPath, '/')
		if j < 0 {
			j = len(pdoc.ImportPath)
		}
	}
	for {
		if i != 0 {
			buf.WriteString(`<span class="muted">/</span>`)
		}
		link := j < len(pdoc.ImportPath) || page == "imp"
		if link {
			buf.WriteString(`<a href="/`)
			buf.WriteString(urlFn(pdoc.ImportPath[:j]))
			buf.WriteString(`">`)
		} else {
			buf.WriteString(`<span class="muted">`)
		}
		buf.WriteString(template.HTMLEscapeString(pdoc.ImportPath[i:j]))
		if link {
			buf.WriteString("</a>")
		} else {
			buf.WriteString("</span>")
		}
		i = j + 1
		if i >= len(pdoc.ImportPath) {
			break
		}
		j = strings.IndexRune(pdoc.ImportPath[i:], '/')
		if j < 0 {
			j = len(pdoc.ImportPath)
		} else {
			j += i
		}
	}
	return buf.String()
}
Example #23
0
File: make.go Project: callistoaz/3
func (s *State) Example(in string) string {
	s.count++

	// extract example source
	in = strings.Replace(in, "@", "\n", -1) // undo raw string hack
	in = strings.Trim(in, "\n")

	// exec input file
	check(ioutil.WriteFile(s.infile(), []byte(in), 0666))
	arg := "-v"
	if *flag_vet {
		arg = "-vet"
	}
	cmd("mumax3", "-cache", "/tmp", arg, s.infile())

	recordExamples(in, s.count)

	return `<a id=example` + fmt.Sprint(s.count) + `></a><pre>` + template.HTMLEscapeString(in) + `</pre>`
}
Example #24
0
func (f *InputField) Build() string {
	// Tag attributes
	attrs := map[string]string{
		"type": f.Type,
		"id":   f.Control.Id,
		"name": f.Control.Id,
	}

	// Add the value if we don't need to reset it every time
	if !f.Control.ResetValue {
		attrs["value"] = template.HTMLEscapeString(f.Control.Value)
	}

	// Add the disabled flag
	if f.Disabled {
		attrs["disabled"] = "disabled"
	}

	// Add the read-only flag
	if f.ReadOnly {
		attrs["readonly"] = "readonly"
	}

	// The place holder
	if f.PlaceHolder != "" {
		attrs["placeholder"] = f.PlaceHolder
	}

	// The CSS classes
	if f.Class != nil {
		attrs["class"] = strings.Join(f.Class, " ")
	}

	// Build the control HTML
	ctrl := "<input"
	for k, v := range attrs {
		ctrl += fmt.Sprintf(" %s=\"%s\"", k, v)
	}
	ctrl += ">"

	return fmt.Sprintf(f.Control.Build(), ctrl)
}
Example #25
0
func esc(s string) string {
	if len(s) == 0 {
		return s
	}
	if isHtml(s) {
		return s
	}
	ss := strings.TrimSpace(s)
	if ss[0] == '<' {
		return fmt.Sprintf("\"%s\"", strings.Replace(s, "\"", "\\\"", -1))
	}
	if isId(s) {
		return s
	}
	if isNumber(s) {
		return s
	}
	if isStringLit(s) {
		return s
	}
	return fmt.Sprintf("\"%s\"", template.HTMLEscapeString(s))
}
Example #26
0
func (c *connection) reader() {
	for {
		var message string
		err := websocket.Message.Receive(c.ws, &message)
		message = template.HTMLEscapeString(message)
		if err != nil {
			break
		}
		if i := strings.Index(message, "name::"); i != -1 {
			name := strings.TrimSpace(message[len("name::"):])

			//check name exist
			for _, v := range clients.memberList() {
				if strings.EqualFold(v, name) || strings.EqualFold("System", name) {
					name = fmt.Sprintf("%s-%d", name, time.Now().Unix()%1000)
					break
				}
			}

			c.name = name
			if q.Len() > 0 {
				c.send <- q.Values.String()
			}
			clients.broadcast <- formatMsg("System", fmt.Sprintf("%s has joined!", name), MSG_WITHMEMBER)

		} else {
			//message = fmt.Sprintf("%s[%s]", message, c.ws.Request().RemoteAddr)
			t := time.Now().In(loc)
			if (int(t.Unix()) - int(c.lastMsgTime.Unix())) < *mf {
				c.send <- formatMsg("System", "you chat frequency too fast!", MSG_WITHMEMBER)
			} else {
				clients.broadcast <- formatMsg(c.name, message, MSG_WITHMEMBER)
				q.Push(formatMsg(c.name, message, MSG_DEFAULT))
				c.lastMsgTime = t
			}
		}
	}
	c.ws.Close()
}
Example #27
0
func (f *TextAreaField) Build() string {
	// Tag attributes
	attrs := map[string]string{
		"rows":        strconv.FormatInt(int64(f.Rows), 10),
		"id":          f.Control.Id,
		"name":        f.Control.Id,
		"placeholder": f.PlaceHolder,
	}

	// The CSS classes
	if f.Class != nil {
		attrs["class"] = strings.Join(f.Class, " ")
	}

	// Build the control HTML
	ctrl := "<textarea"
	for k, v := range attrs {
		ctrl += fmt.Sprintf(" %s=\"%s\"", k, v)
	}
	ctrl += ">" + template.HTMLEscapeString(f.Control.Value) + "</textarea>"

	return fmt.Sprintf(f.Control.Build(), ctrl)
}
Example #28
0
// HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
func HTMLEscapeString(s string) string {
	return template.HTMLEscapeString(s)
}
Example #29
0
//AddTaskFunc is used to handle the addition of new task, "/add" URL
func AddTaskFunc(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" { // Will work only for POST requests, will redirect to home
		r.ParseForm()
		file, handler, err := r.FormFile("uploadfile")
		if err != nil && handler != nil {
			//Case executed when file is uploaded and yet an error occurs
			log.Println(err)
			message = "Error uploading file"
			http.Redirect(w, r, "/", http.StatusInternalServerError)
		}

		taskPriority, priorityErr := strconv.Atoi(r.FormValue("priority"))

		if priorityErr != nil {
			log.Print(priorityErr)
			message = "Bad task priority"
			http.Redirect(w, r, "/", http.StatusInternalServerError)
		}
		priorityList := []int{1, 2, 3}
		found := false
		for _, priority := range priorityList {
			if taskPriority == priority {
				found = true
			}
		}
		//If someone gives us incorrect priority number, we give the priority
		//to that task as 1 i.e. Low
		if !found {
			taskPriority = 1
		}

		category := r.FormValue("category")
		title := template.HTMLEscapeString(r.Form.Get("title"))
		content := template.HTMLEscapeString(r.Form.Get("content"))
		formToken := template.HTMLEscapeString(r.Form.Get("CSRFToken"))

		cookie, _ := r.Cookie("csrftoken")
		if formToken == cookie.Value {
			if handler != nil {
				// this will be executed whenever a file is uploaded
				r.ParseMultipartForm(32 << 20) //defined maximum size of file
				defer file.Close()
				randomFileName := md5.New()
				io.WriteString(randomFileName, strconv.FormatInt(time.Now().Unix(), 10))
				io.WriteString(randomFileName, handler.Filename)
				token := fmt.Sprintf("%x", randomFileName.Sum(nil))
				f, err := os.OpenFile("./files/"+token, os.O_WRONLY|os.O_CREATE, 0666)
				if err != nil {
					log.Println(err)
					return
				}
				defer f.Close()
				io.Copy(f, file)

				filelink := "<br> <a href=/files/" + token + ">" + handler.Filename + "</a>"
				content = content + filelink

				fileTruth := db.AddFile(handler.Filename, token)
				if fileTruth != nil {
					message = "Error adding filename in db"
					log.Println("error adding task to db")
				}
			}

			taskTruth := db.AddTask(title, content, category, taskPriority)

			if taskTruth != nil {
				message = "Error adding task"
				log.Println("error adding task to db")
				http.Redirect(w, r, "/", http.StatusInternalServerError)
			} else {
				message = "Task added"
				log.Println("added task to db")
				http.Redirect(w, r, "/", http.StatusFound)
			}
		} else {
			log.Println("CSRF mismatch")
			message = "Server Error"
			http.Redirect(w, r, "/", http.StatusInternalServerError)
		}

	} else {
		message = "Method not allowed"
		http.Redirect(w, r, "/", http.StatusFound)
	}
}
Example #30
0
func (w *BaseWidget) Render(attrs []string, values ...string) template.HTML {
	w.Attrs().FromSlice(attrs)
	html := fmt.Sprintf(w.HTML, w.Attrs().String(), tTemplate.HTMLEscapeString(values[0]))
	return template.HTML(html)
}