Beispiel #1
0
func formatCode(src []byte, annotations []doc.TypeAnnotation) htemp.HTML {

	// Collect comment positions.
	var (
		comments []doc.TypeAnnotation
		s        scanner.Scanner
	)
	fset := token.NewFileSet()
	file := fset.AddFile("", fset.Base(), len(src))
	s.Init(file, src, nil, scanner.ScanComments)
commentLoop:
	for {
		pos, tok, lit := s.Scan()
		switch tok {
		case token.EOF:
			break commentLoop
		case token.COMMENT:
			p := file.Offset(pos)
			comments = append(comments, doc.TypeAnnotation{Pos: p, End: p + len(lit)})
		}
	}

	// Merge type annotations and comments without modifying the caller's slice
	// of annoations.
	switch {
	case len(comments) == 0:
		// nothing to do
	case len(annotations) == 0:
		annotations = comments
	default:
		annotations = append(comments, annotations...)
		sort.Sort(sortByPos(annotations))
	}

	var buf bytes.Buffer
	last := 0
	for _, a := range annotations {
		htemp.HTMLEscape(&buf, src[last:a.Pos])
		if a.Name != "" {
			p := a.ImportPath
			if p != "" {
				p = "/" + p
			}
			buf.WriteString(`<a href="`)
			buf.WriteString(escapePath(p))
			buf.WriteByte('#')
			buf.WriteString(escapePath(a.Name))
			buf.WriteString(`">`)
			htemp.HTMLEscape(&buf, src[a.Pos:a.End])
			buf.WriteString(`</a>`)
		} else {
			buf.WriteString(`<span class="com">`)
			htemp.HTMLEscape(&buf, src[a.Pos:a.End])
			buf.WriteString(`</span>`)
		}
		last = a.End
	}
	htemp.HTMLEscape(&buf, src[last:])
	return htemp.HTML(buf.String())
}
Beispiel #2
0
func renderElement(element interface{}, contextChain []interface{}, buf io.Writer) error {
	switch elem := element.(type) {
	case *textElement:
		buf.Write(elem.text)
	case *varElement:
		defer func() {
			if r := recover(); r != nil {
				fmt.Printf("Panic while looking up %q: %s\n", elem.name, r)
			}
		}()
		val, err := lookup(contextChain, elem.name, AllowMissingVariables)
		if err != nil {
			return err
		}

		if val.IsValid() {
			if elem.raw {
				fmt.Fprint(buf, val.Interface())
			} else {
				s := fmt.Sprint(val.Interface())
				template.HTMLEscape(buf, []byte(s))
			}
		}
	case *sectionElement:
		if err := renderSection(elem, contextChain, buf); err != nil {
			return err
		}
	case *Template:
		if err := elem.renderTemplate(contextChain, buf); err != nil {
			return err
		}
	}
	return nil
}
Beispiel #3
0
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method)
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		fmt.Println("crutime = ", crutime)
		h := md5.New()
		s := strconv.FormatInt(crutime, 10)
		fmt.Println("s = ", s)
		io.WriteString(h, s)
		fmt.Println("h's md5 = ", h.Sum(nil))
		token := fmt.Sprintf("%x", h.Sum(nil))
		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, token)
	} else {
		r.ParseForm()
		token := r.Form.Get("token")
		if token != "" {
			fmt.Println("token is ", token)
		} else {
			fmt.Println("token is not exists ")
		}
		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")))
	}
}
Beispiel #4
0
func Example_escape() {
	const s = `"Fran & Freddie's Diner" <*****@*****.**>`
	v := []interface{}{`"Fran & Freddie's Diner"`, ' ', `<*****@*****.**>`}

	fmt.Println(template.HTMLEscapeString(s))
	template.HTMLEscape(os.Stdout, []byte(s))
	fmt.Fprintln(os.Stdout, "")
	fmt.Println(template.HTMLEscaper(v...))

	fmt.Println(template.JSEscapeString(s))
	template.JSEscape(os.Stdout, []byte(s))
	fmt.Fprintln(os.Stdout, "")
	fmt.Println(template.JSEscaper(v...))

	fmt.Println(template.URLQueryEscaper(v...))

	// Output:
	// &#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;[email protected]&gt;
	// &#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;[email protected]&gt;
	// &#34;Fran &amp; Freddie&#39;s Diner&#34;32&lt;[email protected]&gt;
	// \"Fran & Freddie\'s Diner\" \[email protected]\x3E
	// \"Fran & Freddie\'s Diner\" \[email protected]\x3E
	// \"Fran & Freddie\'s Diner\"32\[email protected]\x3E
	// %22Fran+%26+Freddie%27s+Diner%2232%3Ctasty%40example.com%3E

}
Beispiel #5
0
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method: ", r.Method)
	if r.Method == "GET" {
		curtime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(curtime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))
		t, _ := template.ParseFiles("login.html")
		t.Execute(w, token)
	} else {
		r.ParseForm()
		token := r.Form.Get("token")
		if token != "" {
			fmt.Println("token is ok")
		} else {
			fmt.Println("token is error")
		}
		slice := []string{"apple", "pear", "banana"}
		log.Println(r.Form.Get("fruit"))
		for _, v := range slice {
			if v == r.Form.Get("fruit") {
				fmt.Println(v)
			}

		}
		log.Println("username: "******"username"])
		log.Println("password: "******"password"])
		template.HTMLEscape(w, []byte(r.Form.Get("username")))
	}
}
Beispiel #6
0
func renderElement(element interface{}, contextChain []interface{}, buf io.Writer) {
	switch elem := element.(type) {
	case string:
		buf.Write([]byte(element.(string)))
	case *textElement:
		buf.Write(elem.text)
	case *varElement:
		defer func() {
			if r := recover(); r != nil {
				fmt.Printf("Panic while looking up %q: %s\n", elem.name, r)
			}
		}()
		val := lookup(contextChain, elem.name)

		if val.IsValid() {
			if elem.raw {
				fmt.Fprint(buf, val.Interface())
			} else {
				s := fmt.Sprint(val.Interface())
				template.HTMLEscape(buf, []byte(s))
			}
		}
	case *sectionElement:
		renderSection(elem, contextChain, buf)
	case *Template:
		elem.renderTemplate(contextChain, buf)
	}
}
Beispiel #7
0
func login(w ResponseWriter, r *Request) {
	Println("方法:", r.Method)
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("login.html")
		t.Execute(w, token)
	} else {
		r.ParseForm()
		token := r.Form.Get("token")
		if token != "" {
			Println("标识:", token)
			// 验证合法性
		} else {
			Println("标识:未获取")
			// 报错
		}
		Println(r)
		Println("用户名长度:", len(r.Form["username"][0]))
		Println("用户名:", template.HTMLEscapeString(r.Form.Get("username")))
		Println("密码:", template.HTMLEscapeString(r.Form.Get("password")))
		template.HTMLEscape(w, []byte(r.Form.Get("username")))
	}
}
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("04-02-03-duplicate-prevention.gtpl")
		t.Execute(w, token)

	} else {
		// log in request
		r.ParseForm()
		token := r.Form.Get("token")

		if token != "" {
			// check token validity
			fmt.Println("TODO: check if the token is valid: %s\n", token)
		} else {
			// give error if no token
			fmt.Println("TODO: handle error as token is not valid!")
		}

		fmt.Printf("Username length: %v\n", len(r.Form["username"][0]))
		fmt.Printf("Username       : %v\n", template.HTMLEscapeString(r.Form.Get("username")))
		fmt.Printf("password       : %v\n", template.HTMLEscapeString(r.Form.Get("password")))
		template.HTMLEscape(w, []byte(r.Form.Get("username")))
	}
}
Beispiel #9
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")

		if token != "" {
			// check token validity
		} else {
			// give error if no 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")))
	}
}
Beispiel #10
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))
		fmt.Println("token", token)
		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, token)
	} else {
		//请求的是登陆数据,那么执行登陆的逻辑判断
		r.ParseForm()
		token := r.Form.Get("token")
		if token != "" {
			//验证 token 的合法性
		} else {
			//不存在 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"))) //输出到客户端
	}
}
Beispiel #11
0
// Write text to w; optionally html-escaped.
func writeText(w io.Writer, text []byte, html bool) {
	if html {
		template.HTMLEscape(w, text)
		return
	}
	w.Write(text)
}
Beispiel #12
0
func codeFn(c doc.Code, typ *doc.Type) htemp.HTML {
	var buf bytes.Buffer
	last := 0
	src := []byte(c.Text)
	for _, a := range c.Annotations {
		htemp.HTMLEscape(&buf, src[last:a.Pos])
		switch a.Kind {
		case doc.PackageLinkAnnotation:
			p := "/" + c.Paths[a.PathIndex]
			buf.WriteString(`<a href="`)
			buf.WriteString(escapePath(p))
			buf.WriteString(`">`)
			htemp.HTMLEscape(&buf, src[a.Pos:a.End])
			buf.WriteString(`</a>`)
		case doc.ExportLinkAnnotation, doc.BuiltinAnnotation:
			var p string
			if a.Kind == doc.BuiltinAnnotation {
				p = "/builtin"
			} else if a.PathIndex >= 0 {
				p = "/" + c.Paths[a.PathIndex]
			}
			n := src[a.Pos:a.End]
			n = n[bytes.LastIndex(n, period)+1:]
			buf.WriteString(`<a href="`)
			buf.WriteString(escapePath(p))
			buf.WriteByte('#')
			buf.WriteString(escapePath(string(n)))
			buf.WriteString(`">`)
			htemp.HTMLEscape(&buf, src[a.Pos:a.End])
			buf.WriteString(`</a>`)
		case doc.CommentAnnotation:
			buf.WriteString(`<span class="com">`)
			htemp.HTMLEscape(&buf, src[a.Pos:a.End])
			buf.WriteString(`</span>`)
		case doc.AnchorAnnotation:
			buf.WriteString(`<span id="`)
			if typ != nil {
				htemp.HTMLEscape(&buf, []byte(typ.Name))
				buf.WriteByte('.')
			}
			htemp.HTMLEscape(&buf, src[a.Pos:a.End])
			buf.WriteString(`">`)
			htemp.HTMLEscape(&buf, src[a.Pos:a.End])
			buf.WriteString(`</span>`)
		default:
			htemp.HTMLEscape(&buf, src[a.Pos:a.End])
		}
		last = int(a.End)
	}
	htemp.HTMLEscape(&buf, src[last:])
	return htemp.HTML(buf.String())
}
Beispiel #13
0
func TestHTMLEscape(t *testing.T) {
	const s = `"Fran & Freddie's Diner" <*****@*****.**>`
	v := []interface{}{`"Fran & Freddie's Diner"`, ' ', `<*****@*****.**>`}

	fmt.Println(template.HTMLEscapeString(s))
	template.HTMLEscape(os.Stdout, []byte(s))
	fmt.Fprint(os.Stdout, "")

	fmt.Println(template.JSEscapeString(s))
	fmt.Println(template.JSEscaper(v...))
	fmt.Println(template.URLQueryEscaper(v...))
}
Beispiel #14
0
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method: ", r.Method)
	if r.Method == "GET" {
		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, nil)
	} else {
		r.ParseForm()
		fmt.Println("username:"******"username")))
		fmt.Println("password:"******"password")))
		template.HTMLEscape(w, []byte(r.Form.Get("username")))
	}
}
Beispiel #15
0
func villagePreWriteHandler(w http.ResponseWriter, r *http.Request) {
	c := gae.NewContext(r)
	g := goon.FromContext(c)
	u := user.Current(c)
	preWriteView := view.PreWriteView{}
	buf := new(bytes.Buffer)
	template.HTMLEscape(buf, []byte(r.FormValue("comment")))
	t := buf.String()
	preWriteView.Text = strings.Replace(t, "\n", "<br>", -1)
	preWriteView.HiddenText = r.FormValue("comment")
	commentType := r.FormValue("commentType")
	characterID := r.FormValue("characterID")
	preWriteView.CharacterID = characterID
	if commentType == "personal" {
		preWriteView.IsPersonal = true
	} else if commentType == "whisper" {
		preWriteView.IsWhisper = true
	} else if commentType == "graveyard" {
		preWriteView.IsGraveyard = true
	} else {
		preWriteView.IsPublic = true
	}
	no, err := strconv.ParseInt(r.FormValue("vno"), 10, 64)
	if err != nil || len(preWriteView.Text) <= 5 || user.Current(c) == nil || len(preWriteView.Text) > 1000 {
		bad(w)
		return
	}
	preWriteView.VillageNo = no
	village := Village{No: no}
	if err := g.Get(&village); err != nil {
		bad(w)
		return
	}
	vKey := g.Key(village)
	person := Person{UserID: u.ID, ParentKey: vKey, CharacterID: characterID}
	if err := g.Get(&person); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	preWriteView.Face = person.Face
	preWriteView.Author = person.Name
	if err = prewriteTmpl.ExecuteTemplate(w, "base", preWriteView); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Beispiel #16
0
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("request method:", r.Method)
	if r.Method == "GET" {
		curtime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(curtime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))
		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, token)

	} else {
		fmt.Println("username: "******"username"))
		fmt.Println("password: "******"password"))
		//		fmt.Fprintln(w, r.FormValue("username"))
		template.HTMLEscape(w, []byte(r.FormValue("username")))
	}

}
Beispiel #17
0
func markText(text string, tokens stringsp.Set, markFunc func([]byte) []byte) template.HTML {
	if len(text) == 0 {
		return ""
	}
	var outBuf bytesp.Slice

	index.MarkText([]byte(text), gcse.CheckRuneType, func(token []byte) bool {
		// needMark
		return tokens.Contain(gcse.NormWord(string(token)))
	}, func(text []byte) error {
		// output
		template.HTMLEscape(&outBuf, text)
		return nil
	}, func(token []byte) error {
		outBuf.Write(markFunc(token))
		return nil
	})
	return template.HTML(string(outBuf))
}
Beispiel #18
0
func renderElement(element interface{}, contextChain []interface{}, buf io.Writer) {
	switch elem := element.(type) {
	case *textElement:
		buf.Write(elem.text)
	case *varElement:
		defer func() {
			if r := recover(); r != nil {
				fmt.Printf("Panic while looking up %q: %s\n", elem.name, r)
			}
		}()
		val := lookup(contextChain, elem.name)

		if val.IsValid() {
			i := val.Interface()

			var content interface{}

			switch fn := reflect.ValueOf(i); fn.Kind() {
			case reflect.Func:
				out := fn.Call(nil)
				if len(out) > 0 && out[0].Kind() == reflect.String {
					content = evaluate(out[0].String(), defaultOtag, defaultCtag, contextChain)
				} else {
					content = ""
				}

			default:
				content = i
			}

			if elem.raw {
				fmt.Fprint(buf, content)
			} else {
				s := fmt.Sprint(content)
				template.HTMLEscape(buf, []byte(s))
			}
		}
	case *sectionElement:
		renderSection(elem, contextChain, buf)
	case *Template:
		elem.renderTemplate(contextChain, buf)
	}
}
Beispiel #19
0
/**
* this pattern of request process, isn't it similar to an abused JSP code? if (method == "GET") {..} else {..}
 */
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("client Method: ", r.Method)
	if r.Method == "GET" { //GET means user just reach login panel
		session, _ := glbSess.CreateOrUpdateSession(w, r)
		fmt.Println("GET to retouch session:", session)

		t, _ := template.ParseFiles("login.gtpl")
		//t.Execute(w, nil)
		t.Execute(w, withToken())
	} else { //POST means user try to login
		r.ParseForm()                                    //by default form will not be parsed until call out,
		fmt.Println("username: "******"username"][0]) //only after ParseForm() was called,
		fmt.Println("password: "******"password"])    //these fields can read value

		//validate token (usually we use session store & compare)
		//token := r.Form["token"] //Form[field] result is []string
		token := r.FormValue("token") //or r.Form["token"][0]
		if token != "" {
			fmt.Println("token: ", token, "submitted")
		} else {
			fmt.Println("Aiyo no token!")
		}

		//check session
		session, _ := glbSess.CreateOrUpdateSession(w, r)
		currUsrName, exists := session.Attributes["username"]
		if !exists || session.IsExpired() {
			currUsrName = r.Form.Get("username")
			session.Attributes["username"] = currUsrName
		} else {
			fmt.Println("Current you have been login as:", currUsrName)
		}

		//output to page should be escaped in case of injection/CRSF attack
		template.HTMLEscape(w, []byte("Welcome "+currUsrName))
	}

	gosessionId, _ := r.Cookie("gosessionid")
	fmt.Println("Your gosessionid is:", gosessionId.Value)
	fmt.Println("Current session object is:", glbSess.GetSession(gosessionId.Value))
	fmt.Println("global session:", glbSess)
}
Beispiel #20
0
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Aceess /login and Method is", 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.html")
		t.Execute(w, token)
	} else {
		r.ParseForm()
		token := r.Form.Get("token")
		if token == "" {
		}
		fmt.Println("username length:", len(r.Form["username"][0]))
		fmt.Println("username:"******"username")))
		fmt.Println("password:"******"password")))
		out := fmt.Sprint(r.Form.Get("username"), " login.")
		template.HTMLEscape(w, []byte(out))
	}
}
Beispiel #21
0
func markText(text string, tokens villa.StrSet,
	markFunc func([]byte) []byte) template.HTML {
	if len(text) == 0 {
		return ""
	}

	var outBuf villa.ByteSlice

	index.MarkText([]byte(text), CheckRuneType, func(token []byte) bool {
		// needMark
		return tokens.In(normWord(string(token)))
	}, func(text []byte) error {
		// output
		template.HTMLEscape(&outBuf, text)
		return nil
	}, func(token []byte) error {
		outBuf.Write(markFunc(token))
		return nil
	})

	return template.HTML(string(outBuf))
}
Beispiel #22
0
func (hw *htmlWriter) writeEscape(s string) {
	htmlTemplate.HTMLEscape(hw.w, []byte(s))
}
Beispiel #23
0
func villageHandler(w http.ResponseWriter, r *http.Request) {
	c := gae.NewContext(r)
	g := goon.FromContext(c)
	no, err := strconv.ParseInt(r.FormValue("vno"), 10, 64)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	village := Village{No: no}
	err = g.Get(&village)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	vKey := g.Key(village)
	schedule := UpdateSchedule{VillageNo: no}
	err = g.Get(&schedule)
	updateNoticeText := ""
	if err != nil {
		updateNoticeText = fmt.Sprintf("更新設定(%d:%02d)", village.UpdatetimeHour, village.UpdatetimeMinute)
	} else {
		t := schedule.UpdateTime.In(jst)
		updateNoticeText = fmt.Sprintf("%d/%d/%d %d時%02d分 頃", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute())
	}
	day, err := strconv.Atoi(r.URL.Query().Get("day"))
	if err != nil {
		if r.URL.Query().Get("day") == "recent" {
			day = village.Day
			if day <= -1 {
				day = -1
			}
		} else {
			day = 0
		}
	}
	page, err := strconv.Atoi(r.URL.Query().Get("page"))
	if err != nil {
		if r.URL.Query().Get("day") == "recent" {
			page = -1
		} else {
			page = 0
		}
	}
	// Illegal Access
	if (day == -1 && village.Day >= 0) || (day > village.Day && village.Day >= 0) || day < -1 {
		http.NotFound(w, r)
		return
	}
	villageView := view.VillageView{
		No:               no,
		CharacterSet:     characterSet,
		Village:          village,
		Day:              day,
		UpdatetimeNotice: updateNoticeText,
		NpcName:          setting.NpcName,
	}
	u := user.Current(c)
	if u != nil {
		villageView.Login = true
		villageView.LogoutURL, _ = user.LogoutURL(c, r.URL.String())
	} else {
		villageView.Login = false
		villageView.LoginURL, _ = user.LoginURL(c, r.URL.String())
	}
	q1 := datastore.NewQuery("Person").Ancestor(vKey).Order("CreatedTime")
	people := make([]Person, 0, 10)
	if _, err := g.GetAll(q1, &people); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	villageView.People = people
	var reader Person
	for _, person := range people {
		if u != nil && person.UserID == u.ID {
			villageView.Enter = true
			villageView.UserFace = person.Face
			if village.Day > 0 {
				villageView.ShowAbility = true
				villageView.AbilityDescription = person.Job.Description()
				if person.Job.CanUseAbility(village.Day) && !person.Dead {
					villageView.ShowAbilitySelect = true
				}
			}
			reader = person
			villageView.Reader = person
			break
		}
	}
	if u != nil && village.Builder == u.ID && village.NumberOfPeople >= 8 && village.Day == 0 {
		villageView.ShowStartButton = true
	}
	posts := make([]Post, 0, 30)
	memPostKey := memcacheKey("Post", no, day)
	if cache, err := memcache.Get(c, memPostKey); err == memcache.ErrCacheMiss {
		q2 := datastore.NewQuery("Post").Ancestor(vKey).Filter("Day =", day).Order("Time")
		if _, err := g.GetAll(q2, &posts); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if val, err := serialize(&posts); err == nil {
			item := memcache.Item{Key: memPostKey, Value: val, Expiration: time.Hour * 12}
			memcache.Add(c, &item)
		}
	} else if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	} else {
		deserialize(cache.Value, &posts)
	}

	viewPosts := make([]Post, 0, 30)
	if villageView.Enter {
		for i := range posts {
			addOK := false
			pType := posts[i].Type
			if village.Day <= -1 {
				addOK = true
			} else if (pType == Personal || pType == SystemSecret) && posts[i].AuthorID == reader.UserID {
				addOK = true
			} else if (pType == Whisper) && reader.Job.CanSpeakWhisper() {
				addOK = true
			} else if pType == Public || pType == SystemMessage {
				addOK = true
			} else if pType == Graveyard && reader.Dead {
				addOK = true
			}
			if addOK {
				viewPosts = append(viewPosts, posts[i])
			}
		}
	} else {
		for i := range posts {
			if village.Day <= -1 || posts[i].Type == Public || posts[i].Type == SystemMessage {
				viewPosts = append(viewPosts, posts[i])
			}
		}
	}
	var maxPage int
	if len(viewPosts) > 19 {
		maxPage = (len(viewPosts) / 15)
		if page == -1 || page >= maxPage {
			viewPosts = viewPosts[len(viewPosts)-15:]
			if day == -1 || day == village.Day {
				villageView.Recent = true
			}
		} else {
			viewPosts = viewPosts[15*page : 15*(page+1)]
		}
	} else {
		maxPage = 0
		if day == -1 || day == village.Day {
			villageView.Recent = true
		}
	}
	villageView.Posts = viewPosts
	villageView.Indexes = make([]view.Page, maxPage+1)
	for i := 0; i <= maxPage; i++ {
		p := view.Page{Number: i}
		if page == i {
			p.Invalid = true
		}
		villageView.Indexes[i] = p
	}

	for i, po := range villageView.Posts {
		buf := new(bytes.Buffer)
		template.HTMLEscape(buf, []byte(po.Text))
		t := buf.String()
		t = strings.Replace(t, "\n", "<br />", -1)
		villageView.Posts[i].Text = t
	}

	chap := []view.Chapter{view.Chapter{Day: 0, Name: "プロローグ", Invalid: day == 0}}
	if d := village.Day; d > 0 {
		for i := 1; i <= village.Day; i++ {
			chap = append(chap, view.Chapter{Day: i, Name: strconv.Itoa(i) + "日目", Invalid: day == i})
		}
	} else if d < 0 {
		d *= -1
		for i := 1; i < d; i++ {
			chap = append(chap, view.Chapter{Day: i, Name: strconv.Itoa(i) + "日目", Invalid: day == i})
		}
		chap = append(chap, view.Chapter{Day: -1, Name: "エピローグ", Invalid: day == -1})
	}
	villageView.Chapters = chap
	if day == -1 && village.Day <= -1 {
		villageView.ShowResult = true
		rCols := make([]view.ResultCol, 0, 10)
		j := Judge(people)
		for i := range people {
			rc := view.ResultCol{Name: people[i].Name, Dead: people[i].Dead, Job: people[i].Job, Victory: people[i].Job.GotVictory(j)}
			if people[i].WantJob == "1" {
				rc.WantJob = "おまかせ"
			} else if people[i].WantJob == "2" {
				rc.WantJob = "村陣営"
			} else if people[i].WantJob == "3" {
				rc.WantJob = "村陣営(役職)"
			} else if people[i].WantJob == "4" {
				rc.WantJob = "人外陣営"
			}
			user := User{ID: people[i].UserID}
			if err := g.Get(&user); err != nil {
				rc.Handle = "Unknown"
			} else {
				rc.Handle = user.Handle
			}
			rCols = append(rCols, rc)
		}
		villageView.Result = rCols
	}
	if err := villagePageTmpl.ExecuteTemplate(w, "base", villageView); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Beispiel #24
0
func login(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Println("method:", r.Method) //获取请求方法
	if r.Method == "GET" {

		t := template.Must(template.ParseFiles("login.gtpl"))
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := t.Execute(w, nil); err != nil {
			fmt.Println(err)
		}
	} else {
		//请求的是登陆数据,那么执行登陆逻辑判断
		fmt.Println("username:"******"username"])
		fmt.Println("password:"******"password"])

		//request.Form是一个url.Values类型,里面存储的是对应的类似key=value的信息,下面展示了可以对form数据
		//进行的一些操作:
		v := r.Form
		v.Set("name", "Ava")
		v.Add("friend", "Jess")
		v.Add("friend", "Sarah")
		v.Add("friend", "Zoe")
		// v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe"
		fmt.Println(v.Get("name"))
		fmt.Println(v.Get("friend"))
		fmt.Println(v["friend"])

		//表单处理
		if len(r.Form["username"][0]) == 0 {
		}

		getint, err := strconv.Atoi(r.Form.Get("age"))
		if err != nil {
			//数字转化错误,那么可能就不是数字
		}

		if getint > 100 {
			//太大了
		}

		if m, _ := regexp.MatchString("^[0-9]+$", r.Form.Get("age")); !m {
			//正则匹配
		}

		//判断是否为中午
		if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", r.Form.Get("realname")); !m {

		}

		//判断是否英文
		if m, _ := regexp.MatchString("^[a-zA-Z]+$", r.Form.Get("engname")); !m {

		}

		//邮件号码
		if m, _ := regexp.MatchString(`^([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})$`, r.Form.Get("email")); !m {
			fmt.Println("no")
		} else {
			fmt.Println("yes")
		}

		//手机号码
		if m, _ := regexp.MatchString(`^(1[3|4|5|8][0-9]\d{4,8})$`, r.Form.Get("mobile")); !m {

		}

		//数组存在判断
		/*
			slice:=[]string{"apple","pear","banane"}
			for _, v := range slice {
				if v == r.Form.Get("fruit") {
					return true
				}
			}
			return false
		*/
		//时间
		t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
		fmt.Printf("Go launched at %s\n", t.Local())

		//身份证
		if m, _ := regexp.MatchString(`^(\d{15})$`, r.Form.Get("usercard")); !m {

		}

		//XSS
		/*
			func HTMLEscape(w io.Writer, b []byte) //把b进行转义之后写到w
			func HTMLEscapeString(s string) string //转义s之后返回结果字符串
			func HTMLEscaper(args …interface{}) string //支持多个参数一起转义,返回结果字符串
		*/
		fmt.Println("username:"******"username"))) //输出到服务器端
		fmt.Println("password:"******"password")))
		template.HTMLEscape(w, []byte(r.Form.Get("username"))) //输出到客户端

		//模板中的变量会自行转义 为防止使用template.HTML

		/*
			t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
			err = t.ExecuteTemplate(out, "T", template.HTML("<script>alert('you have been pwned')</script>"))
		*/

	}
}
Beispiel #25
0
// Template formatter for "htmlesc" format.
func htmlEscFmt(w io.Writer, format string, x ...interface{}) string {
	var buf bytes.Buffer
	writeAny(&buf, false, x[0])
	template.HTMLEscape(w, buf.Bytes())
	return ""
}
Beispiel #26
0
func markWord(word []byte) []byte {
	buf := villa.ByteSlice("<b>")
	template.HTMLEscape(&buf, word)
	buf.Write([]byte("</b>"))
	return buf
}
Beispiel #27
0
func UrlHtmlFormatter(w io.Writer, fmt string, v ...interface{}) {
	template.HTMLEscape(w, []byte(http.URLEscape(v[0].(string))))
	// 	fmt.Fprintln(w, "dsdsd\nasdfasdf\tasdfasdf\"tile\"")
}
Beispiel #28
0
func login(w http.ResponseWriter, r *http.Request) {
	//fmt.Println("method:",r.Method)
	//fmt.Println("scheme", r.URL.Scheme)
	sess := globalSessions.SessionStart(w, r)
	r.ParseForm()
	if r.Method == "GET" {
		curtime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(curtime, 10))
		//token := fmt.Sprintf("%x",h.Sum(nil))
		t, _ := template.ParseFiles("login.html")
		//t.Execute(w,token)
		t.Execute(w, sess.Get("username"))
	} else {
		//fmt.Println("username:"******"username"])
		//fmt.Println("password:"******"password"])
		sess.Set("username", r.Form["username"])
		http.Redirect(w, r, "/count", 302)
		fmt.Println(r.Form)
		fmt.Fprintln(w, r.Form)
		if len(r.Form["username"][0]) == 0 {
			fmt.Fprintln(w, "username is empty..")
		}

		if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", r.Form.Get("username")); m {
			fmt.Fprintln(w, "username is Chinese charactor.")
		}

		if m, _ := regexp.MatchString("^[0-9]+$", r.Form.Get("age")); m {
			fmt.Fprintln(w, "Age is a number.")
		}

		getint, err := strconv.Atoi(r.Form.Get("age"))
		if err != nil {
			fmt.Fprintln(w, "not a number...")
		} else if getint > 100 {
			fmt.Fprintln(w, getint, "is a large number...")
		}

		if m, _ := regexp.MatchString(`^([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})$`, r.Form.Get("email")); m {
			fmt.Fprintln(w, "a valid email", r.Form.Get("email"))
		}

		slicefruit := []string{"apple", "pear", "banana"}
		for _, v := range slicefruit {
			if v == r.Form.Get("fruit") {
				fmt.Fprintln(w, "fruit is", r.Form.Get("fruit"))
			}
		}

		slicegender := []string{"1", "2"}
		mapgender := make(map[string]string)
		mapgender["1"] = "male"
		mapgender["2"] = "female"

		for _, v := range slicegender {
			if v == r.Form.Get("gender") {
				fmt.Fprintln(w, "Gender is", mapgender[r.Form.Get("gender")])
			}
		}
		//fmt.Fprintf(w,"username: %s, password: %s",r.Form["username"],r.Form["password"])
		fmt.Println("username:"******"username")))
		fmt.Println("password:"******"password")))
		template.HTMLEscape(w, []byte(r.Form.Get("username")))
	}
}