コード例 #1
0
ファイル: npc.go プロジェクト: sintell/TheTower
func GetNpcs() (npcs []*Npc) {
	var data []NpcInfo
	err := utils.LoadSetting(&data, "data/npc.json")
	if err != nil {
		panic(err.Error())
	}

	for _, npcType := range data {
		for _, location := range npcType.Locations {
			for locName, count := range location {
				counter := 0
				npcClass := npcType.Class
				npcBehavior := npcType.Behavior
				for i := 0; i < count; i++ {
					counter++
					npc := &Npc{
						Character{
							Name:            fmt.Sprintf("%s#%d", strings.ToTitle(npcBehavior), counter),
							Class:           npcClass,
							CurrentLocation: locName,
							OwnerUid:        fmt.Sprintf("%s#%d", strings.ToTitle(npcBehavior), counter),
						},
						ai.Behavior(npcBehavior),
					}
					npc.SetDefaults()
					npcs = append(npcs, npc)

				}
			}

		}
	}

	return
}
コード例 #2
0
ファイル: main.go プロジェクト: kheyalimitra/GeNA-Miner-Site
func ExampleToTitle() {
	fmt.Println(strings.ToTitle("loud noises"))
	fmt.Println(strings.ToTitle("хлеб"))
	// Output:
	// LOUD NOISES
	// ХЛЕБ
}
コード例 #3
0
ファイル: main.go プロジェクト: suifengRock/go-source
func main() {
	fmt.Println(strings.Index("chicken", "ken"))
	fmt.Println(strings.Index("chicken", "dmr"))

	fmt.Println(strings.ContainsAny("team", "e"))
	fmt.Println(strings.ContainsAny("failure", "u & i"))
	fmt.Println(strings.ContainsAny("foo", ""))
	fmt.Println(strings.ContainsAny("", ""))

	fmt.Println(1 & 1)
	fmt.Println(2 & 1)
	fmt.Println(4 & 1)
	fmt.Println(5 & 1)

	pow, sq := HashTest("1234567")
	fmt.Println(pow)
	fmt.Println(sq)

	str := "df 世 界 asd"
	s := "1界"
	index := strings.IndexAny(str, "界")
	fmt.Printf("%d......\n", index)
	for i, c := range str {
		fmt.Println(i)
		for _, m := range s {
			fmt.Printf("%c\t%c\n", c, m)
		}
	}

	for i := len(str); i > 0; {
		rune, size := utf8.DecodeLastRuneInString(str[0:i])
		fmt.Printf("%v\t", i)
		i -= size
		for _, m := range s {
			fmt.Printf("%c\t%v\t%v\n", rune, size, m)
		}
	}

	fmt.Println("bytes =", len(str))
	fmt.Println("runes =", utf8.RuneCountInString(str))

	for _, ss := range strings.Fields(str) {
		fmt.Println(ss)

	}
	fmt.Println(strings.ToTitle(str))

	str = "Hello, 世界"

	// for len(str) > 0 {
	// 	r, size := utf8.DecodeRuneInString(str)
	// 	fmt.Printf("%c %v\n", r, size)

	// 	str = str[size:]
	// }
	fmt.Println(Replace(str, "", "f", -1))

	hulu := new(huluwa)
	hello(hulu)
}
コード例 #4
0
ファイル: template.go プロジェクト: WalterShe/wfdr
// Renders a set of data provided by the module into the format specified by the request. Normally, this means that the data is rendered into HTML (mobile vs. desktop is automatically selected), but we may add support for ?alt=json or such at a later point
func Render(c http.ResponseWriter, r *http.Request, title, name string, data interface{}) {
	if WouldUseJson(r) {
		enc := json.NewEncoder(c)
		err := enc.Encode(data)
		if err != nil {
			Error500(c, r, err)
		}
		return
	}
	var p PageInfo
	if title == "" {
		title = strings.ToTitle(moduleName)
	}
	// 	if moduleName == "unknown" {
	// 		log.Println("Warning: Attempting to render a template without moduleName being set! Call SetModuleName during the initialization of your module in order to correct this (in main()).")
	// 	}
	p.Title = title
	// Removed the modulename because it's not needed in the new framework. However, this will break things in the old framework. *sigh*...
	p.Name = /*moduleName + "/" + */ name
	p.Request = r
	perms, err := perms.Get(r)
	if err != nil {
		log.Printf("Warning: Error getting page permissions for %s: %s", r.URL, err)
	}
	p.Perms = perms
	p.Object = data

	err = Execute(c, &p)
	if err != nil {
		c.WriteHeader(500)
		fmt.Fprintln(c, "FATAL ERROR:", err)
		return
	}
}
コード例 #5
0
ファイル: http_tamperer.go プロジェクト: roger2000hk/muxy
func (m *HttpTampererSymptom) MuckRequest(ctx *muxy.Context) {

	// Body
	if m.Request.Body != "" {
		newreq, err := http.NewRequest(ctx.Request.Method, ctx.Request.URL.String(), bytes.NewBuffer([]byte(m.Request.Body)))
		if err != nil {
			log.Error(err.Error())
		}
		*ctx.Request = *newreq
		log.Debug("Spoofing HTTP Request Body with %s", log.Colorize(log.BLUE, m.Request.Body))
	}

	// Set Cookies
	for _, c := range m.Request.Cookies {
		c.Expires = stringToDate(c.RawExpires)
		log.Debug("Spoofing Request Cookie %s => %s", log.Colorize(log.LIGHTMAGENTA, c.Name), c.String())
		ctx.Request.Header.Add("Cookie", c.String())
	}

	// Set Headers
	for k, v := range m.Request.Headers {
		key := strings.ToTitle(strings.Replace(k, "_", "-", -1))
		log.Debug("Spoofing Request Header %s => %s", log.Colorize(log.LIGHTMAGENTA, key), v)
		ctx.Request.Header.Set(key, v)
	}

	// This Writes all headers, setting status code - so call this last
	if m.Request.Method != "" {
		ctx.Request.Method = m.Request.Method
	}
}
コード例 #6
0
ファイル: utils.go プロジェクト: jmptrader/jra-go
func titleCaseFirstLetter(in string) string {
	out := ""
	out += string(in[0])
	out = strings.ToTitle(out)
	out += in[1:]
	return out
}
コード例 #7
0
ファイル: config.go プロジェクト: Archieeeeee/secretun
func convertStruct(in interface{}, val reflect.Value) *ConfigError {
	dict, ok := in.(map[string]interface{})
	if !ok || len(dict) != val.NumField() {
		return &ConfigError{ErrInvalidType, ""}
	}

	for k, from := range dict {
		to := val.FieldByName(strings.ToTitle(k[:1]) + k[1:])
		if !to.IsValid() {
			return &ConfigError{ErrInvalidType, ""}
		}

		convertor := convertFuncs.get(to)
		if convertor == nil {
			return &ConfigError{ErrInvalidType, ""}
		}

		if err := convertor(from, to); err != nil {
			if len(err.Field) > 0 {
				err.Field = fmt.Sprintf("%s.%s", k, err.Field)
			} else {
				err.Field = k
			}
			return err
		}
	}

	return nil
}
コード例 #8
0
ファイル: measure.go プロジェクト: thnguyn2/WebGPU
func doLogGPUStatus() {

	var stdout, stderr bytes.Buffer
	logGPU := func(toLog string) {
		cmd := exec.Command("nvidia-smi ",
			"-q", "-d", toLog, "|", "grep", "Gpu", "|", "cut", "-c35-36")
		cmd.Stdout = &stdout
		cmd.Stderr = &stderr

		err := RunCommandWithTimeout(5*time.Second, cmd)
		if err != nil {
			switch err.(type) {
			case TimeoutError:
				Incr(ServerRole+"-System", "GPUUnResponsive")
				return
			}
		} else {
			Log("System", strings.ToTitle(toLog),
				string(stdout.Bytes())+"::"+string(stderr.Bytes()))
		}
	}
	logGPU("MEMORY")
	logGPU("UTILIZATION")
	logGPU("PERFORMANCE")
	logGPU("ECC")
	logGPU("CLOCK")
	logGPU("TEMPERATURE")

}
コード例 #9
0
ファイル: dashing.go プロジェクト: technosophos/dashing
func addPlist(name string, config *Dashing) {
	var file bytes.Buffer
	t := template.Must(template.New("plist").Parse(plist))

	fancyName := config.Name
	if len(fancyName) == 0 {
		fancyName = strings.ToTitle(name)
	}

	aj := "false"
	if config.AllowJS {
		aj = "true"
	}

	tvars := map[string]string{
		"Name":        name,
		"FancyName":   fancyName,
		"Index":       config.Index,
		"AllowJS":     aj,
		"ExternalURL": config.ExternalURL,
	}

	err := t.Execute(&file, tvars)
	if err != nil {
		fmt.Printf("Failed: %s\n", err)
		return
	}
	ioutil.WriteFile(name+".docset/Contents/Info.plist", file.Bytes(), 0755)
}
コード例 #10
0
func (tester *TestSearchSpaces) createTestData() ([]space.Space, error) {
	names := []string{"TEST_A", "TEST_AB", "TEST_B", "TEST_C"}
	for i := 0; i < 20; i++ {
		names = append(names, "TEST_"+strconv.Itoa(i))
	}

	spaces := []space.Space{}

	err := application.Transactional(tester.db, func(app application.Application) error {
		for _, name := range names {
			space := space.Space{
				Name:        name,
				Description: strings.ToTitle("description for " + name),
			}
			newSpace, err := app.Spaces().Create(context.Background(), &space)
			if err != nil {
				return err
			}
			spaces = append(spaces, *newSpace)
		}
		return nil
	})
	if err != nil {
		return nil, fmt.Errorf("Failed to insert testdata", err)
	}
	return spaces, nil
}
コード例 #11
0
ファイル: util.go プロジェクト: grafikdb/grafik-public
// TitleCase replace _ with space and upcase every word
func TitleCase(s string) string {
	ss := strings.Fields(strings.Replace(s, "_", " ", -1))
	for i := range ss {
		ss[i] = strings.ToTitle(ss[i][:1]) + ss[i][1:]
	}
	return strings.Join(ss, " ")
}
コード例 #12
0
ファイル: authenticate.go プロジェクト: janiukjf/GoAdmin
func Forgot(w http.ResponseWriter, r *http.Request) {
	var err error
	var tmpl *plate.Template

	params := r.URL.Query()
	error := params.Get("error")
	error, _ = url.QueryUnescape(error)
	server := plate.NewServer()

	tmpl, err = server.Template(w)

	if err != nil {
		plate.Serve404(w, err.Error())
		return
	}

	tmpl.Bag["PageTitle"] = "Forgot Password"
	tmpl.Bag["Error"] = strings.ToTitle(error)
	tmpl.Bag["CurrentYear"] = time.Now().Year()
	tmpl.Bag["userID"] = 0

	tmpl.FuncMap["isNotNull"] = func(str string) bool {
		if strings.TrimSpace(str) != "" && len(strings.TrimSpace(str)) > 0 {
			return true
		}
		return false
	}
	tmpl.FuncMap["isLoggedIn"] = func() bool {
		return false
	}

	templates := append(TemplateFiles, "templates/auth/forgot.html")

	tmpl.DisplayMultiple(templates)
}
コード例 #13
0
ファイル: authenticate.go プロジェクト: janiukjf/GoAdmin
func SignUp(w http.ResponseWriter, r *http.Request) {
	var err error
	var tmpl *plate.Template

	params := r.URL.Query()
	error := params.Get("error")
	error, _ = url.QueryUnescape(error)

	fname := params.Get("fname")
	fname, _ = url.QueryUnescape(fname)

	lname := params.Get("lname")
	lname, _ = url.QueryUnescape(lname)

	email := params.Get("email")
	email, _ = url.QueryUnescape(email)

	username := params.Get("username")
	username, _ = url.QueryUnescape(username)

	var submitted bool
	submitted, err = strconv.ParseBool(params.Get("submitted"))
	if err != nil {
		submitted = false
	}

	server := plate.NewServer()

	tmpl, err = server.Template(w)

	if err != nil {
		plate.Serve404(w, err.Error())
		return
	}

	tmpl.Bag["PageTitle"] = "Register"
	tmpl.Bag["Error"] = strings.ToTitle(error)
	tmpl.Bag["Fname"] = strings.TrimSpace(fname)
	tmpl.Bag["Lname"] = strings.TrimSpace(lname)
	tmpl.Bag["Email"] = strings.TrimSpace(email)
	tmpl.Bag["Username"] = strings.TrimSpace(username)
	tmpl.Bag["CurrentYear"] = time.Now().Year()
	tmpl.Bag["Submitted"] = submitted
	tmpl.Bag["userID"] = 0

	tmpl.FuncMap["isNotNull"] = func(str string) bool {
		if strings.TrimSpace(str) != "" && len(strings.TrimSpace(str)) > 0 {
			return true
		}
		return false
	}
	tmpl.FuncMap["isLoggedIn"] = func() bool {
		return false
	}

	templates := append(TemplateFiles, "templates/auth/signup.html")

	tmpl.DisplayMultiple(templates)

}
コード例 #14
0
ファイル: paperkey_phrase_test.go プロジェクト: qbit/client
func TestPaperKeyPhraseTypos(t *testing.T) {
	p, err := MakePaperKeyPhrase(0)
	if err != nil {
		t.Fatal(err)
	}

	equivs := []string{
		p.String(),
		"   " + p.String(),
		p.String() + "  ",
		" " + p.String() + " ",
		"\t" + p.String() + "  ",
		" " + p.String() + "\t",
		strings.Join(strings.Split(p.String(), " "), "   "),
		strings.ToTitle(p.String()),
		strings.ToUpper(p.String()),
	}

	for _, s := range equivs {
		q := NewPaperKeyPhrase(s)
		version, err := q.Version()
		if err != nil {
			t.Fatal(err)
		}
		if version != 0 {
			t.Errorf("input: %q => version: %d, expected 0", s, version)
		}
		if q.String() != p.String() {
			t.Errorf("input: %q => phrase %q, expected %q", s, q.String(), p.String())
		}
		if len(q.InvalidWords()) > 0 {
			t.Errorf("input: %q => phrase %q, contains invalid words %v", s, q.String(), q.InvalidWords())
		}
	}

	// make a typo in one of the words
	w := strings.Fields(p.String())
	w[0] = w[0] + "qx"
	x := strings.Join(w, " ")
	q := NewPaperKeyPhrase(x)

	// version should still be ok
	version, err := q.Version()
	if err != nil {
		t.Fatal(err)
	}
	if version != 0 {
		t.Errorf("input: %q => version: %d, expected 0", x, version)
	}

	// but InvalidWords should return the first word as invalid
	if len(q.InvalidWords()) == 0 {
		t.Fatalf("input: %q => all words valid, expected %s to be invalid", x, w[0])
	}

	if q.InvalidWords()[0] != w[0] {
		t.Errorf("input: %q => invalid words %v, expected %s", x, q.InvalidWords(), w[0])
	}
}
コード例 #15
0
func main() {
	fmt.Println("Hello World")
	fmt.Println(strings.ToTitle("Hello World"))
	fmt.Println(strings.ToLower("hello world"))
	fmt.Println(strings.Replace("Hello World Hello World Hello World", "Hello", "Come", 2))
	fmt.Println(strings.Replace("    Aero    space", "    ", "", 2)) // Remove space
	fmt.Println(strings.TrimSpace("    Aero    space"))              // Also remove space but in the front
}
コード例 #16
0
ファイル: helpers.go プロジェクト: moochi/grender
func NewBlogTuple(path, targetExt string) (BlogTuple, bool) {
	path = filepath.Base(path)
	m := BlogEntryRegexp.FindAllStringSubmatch(path, -1)

	if len(m) <= 0 {
		Debugf("Blog Tuple: %s: failed to parse stage 0", path)
		return BlogTuple{}, false
	}

	if len(m[0]) < 5 {
		Debugf("Blog Tuple: %s: failed to parse stage 1", path)
		return BlogTuple{}, false
	}

	if len(m[0][1]) <= 0 || len(m[0][2]) <= 0 || len(m[0][3]) <= 0 {
		Debugf("Blog Tuple: %s: failed to parse stage 2", path)
		return BlogTuple{}, false
	}

	yyyy, err := strconv.ParseInt(m[0][1], 10, 32)
	if err != nil {
		Debugf("Blog Tuple: %s: bad year '%s'", path, m[1])
		return BlogTuple{}, false
	}

	mm, err := strconv.ParseInt(m[0][2], 10, 32)
	if err != nil {
		Debugf("Blog Tuple: %s: bad month '%s'", path, m[2])
		return BlogTuple{}, false
	}

	dd, err := strconv.ParseInt(m[0][3], 10, 32)
	if err != nil {
		Debugf("Blog Tuple: %s: bad day '%s'", path, m[3])
		return BlogTuple{}, false
	}

	if len(m[0][4]) <= 0 {
		Debugf("Blog Tuple: %s: failed to parse stage 3", path)
		return BlogTuple{}, false
	}

	filename := m[0][4]
	title := filename
	title = strings.Replace(title, "-", " ", -1)
	title = strings.Replace(title, "_", " ", -1)
	title = strings.ToTitle(string(title[0])) + title[1:]

	Debugf("Blog Tuple: %s: OK", path)
	return BlogTuple{
		Year:     int(yyyy),
		Month:    int(mm),
		Day:      int(dd),
		Title:    title,
		Filename: filename + targetExt,
	}, true
}
コード例 #17
0
func stringFunktionenXmpl() {
	fmt.Println(strings.ToLower(satz1))
	fmt.Println(strings.ToTitle(satz1))
	fmt.Println(strings.Title(satz1))
	fmt.Println(strings.Count(satz1, "braun"))
	fmt.Println(strings.Fields(satz1)[0])
	fmt.Println(strings.Repeat("Fuchs ", 4))
	fmt.Println(strings.Replace(satz1, "braun", "rot", -1))
}
コード例 #18
0
ファイル: util.go プロジェクト: jpillora/webfont-downloader
func camel2const(s string) string {
	b := bytes.Buffer{}
	var c rune
	start := 0
	end := 0
	for end, c = range s {
		if c >= 'A' && c <= 'Z' {
			//uppercase all prior letters and add an underscore
			if start < end {
				b.WriteString(strings.ToTitle(s[start:end] + "_"))
				start = end
			}
		}
	}
	//write remaining string
	b.WriteString(strings.ToTitle(s[start : end+1]))
	return b.String()
}
コード例 #19
0
func main() {
	s := "heLLo worLd Abc"
	us := strings.ToUpper(s)
	ls := strings.ToLower(s)
	ts := strings.ToTitle(s)
	fmt.Printf("%q\n", us) // "HELLO WORLD ABC"
	fmt.Printf("%q\n", ls) // "hello world abc"
	fmt.Printf("%q\n", ts) // "HELLO WORLD ABC"
}
コード例 #20
0
ファイル: fuzz.go プロジェクト: documize/html-diff
func fuz6(fcfg *fuzzCfg, data []byte, seed uint) {
	raw := string(data)
	x := ""
	for _, r := range raw {
		if r != utf8.RuneError {
			x += string(r)
		}
	}
	fcfg.cmp = []string{x, strings.ToTitle(x)}
}
コード例 #21
0
func show(s string) {
	fmt.Println("\nstring:         ", s, "len:", utf8.RuneCountInString(s))
	fmt.Println("All upper case: ", strings.ToUpper(s)) // DZLJNJ
	fmt.Println("All lower case: ", strings.ToLower(s)) // dzljnj
	fmt.Println("All title case: ", strings.ToTitle(s)) // DzLjNj
	// notice Title() only modifies first letters of words
	// non-first letters keep their case.
	fmt.Println("Title words:    ", strings.Title(s)) //   Dzljnj
	fmt.Println("Swapping case:  ", strings.Map(unicode.SimpleFold, s))
}
コード例 #22
0
ファイル: sql.go プロジェクト: chrislusf/qlbridge
func (m *SqlSource) String() string {

	if int(m.Op) == 0 && int(m.LeftOrRight) == 0 && int(m.JoinType) == 0 {
		if m.Alias != "" {
			return fmt.Sprintf("%s AS %v", m.Name, m.Alias)
		}
		return m.Name
	}
	buf := bytes.Buffer{}
	//u.Warnf("op:%d leftright:%d jointype:%d", m.Op, m.LeftRight, m.JoinType)
	//u.Warnf("op:%s leftright:%s jointype:%s", m.Op, m.LeftRight, m.JoinType)
	//u.Infof("%#v", m)
	//   Jointype                Op
	//  INNER JOIN orders AS o 	ON
	if int(m.JoinType) != 0 {
		buf.WriteString(strings.ToTitle(m.JoinType.String()))
		buf.WriteByte(' ')
	}
	buf.WriteString("JOIN ")

	if m.Alias != "" {
		buf.WriteString(fmt.Sprintf("%s AS %v", m.Name, m.Alias))
	} else {
		buf.WriteString(m.Name)
	}
	buf.WriteByte(' ')
	buf.WriteString(strings.ToTitle(m.Op.String()))

	//u.Warnf("JoinExpr? %#v", m.JoinExpr)
	if m.JoinExpr != nil {
		buf.WriteByte(' ')
		buf.WriteString(m.JoinExpr.String())
		//buf.WriteByte(' ')
	}
	//u.Warnf("source? %#v", m.Source)
	// if m.Source != nil {
	// 	buf.WriteString(m.Source.String())
	// }
	return buf.String()
}
コード例 #23
0
ファイル: main.go プロジェクト: sjn1978/go-fuzz
func Fuzz(data []byte) int {
	s := string(data)
	si := len(s) / 4 * 3
	s0 := s[:si]
	s1 := s[si:]
	s2, r := splitRune(s)
	s3 := s[:len(s)/2]
	s4 := s[len(s)/2:]
	s5 := s[:len(s)/3]
	s6 := s[len(s)/3 : len(s)/3*2]
	s7 := s[len(s)/3*2:]

	strings.Contains(s0, s1)
	strings.ContainsAny(s0, s1)
	strings.ContainsRune(s, r)
	strings.Count(s0, s1)
	strings.EqualFold(s3, s4)
	fields := strings.Fields(s)
	strings.HasPrefix(s0, s1)
	strings.HasSuffix(s0, s1)
	strings.Index(s0, s1)
	strings.IndexAny(s0, s1)
	strings.IndexByte(s2, byte(r))
	strings.IndexRune(s2, r)
	strings.Join(fields, " ")
	strings.LastIndex(s0, s1)
	strings.LastIndexAny(s0, s1)
	strings.Repeat(s, 2)
	strings.Replace(s, s0, s1, -1)
	strings.Split(s0, s1)
	strings.SplitAfter(s0, s1)
	strings.SplitAfterN(s0, s1, 2)
	strings.SplitN(s0, s1, 2)
	strings.Title(s)
	strings.ToLower(s)
	strings.ToLowerSpecial(unicode.AzeriCase, s)
	strings.ToTitle(s)
	strings.ToTitleSpecial(unicode.AzeriCase, s)
	strings.ToUpper(s)
	strings.ToUpperSpecial(unicode.AzeriCase, s)
	strings.Trim(s0, s1)
	strings.TrimLeft(s0, s1)
	strings.TrimPrefix(s0, s1)
	strings.TrimRight(s0, s1)
	strings.TrimSpace(s)
	strings.TrimSuffix(s0, s1)
	strings.NewReplacer(s5, s6).Replace(s7)
	return 0
}
コード例 #24
0
ファイル: server.go プロジェクト: nablaone/golang-sandbox
func EchoServer(ws *websocket.Conn) {
	r := bufio.NewReader(ws)

	for {
		line, err := r.ReadString('\n')
		if err != nil {
			log.Println("ERR:  ", err)
			return
		}
		log.Println("READ:", line)
		out := ">>>> " + strings.ToTitle(line)
		ws.Write([]byte(out))
	}

}
コード例 #25
0
ファイル: post.go プロジェクト: abh/jkl
// Helper function to parse a blog posts filename, which is in the following
// format: YYYY-MM-DD-name-of-post.markdown
//
// the name of the post will be separated from the time of the post, both of
// which are returned by this function
func parsePostName(fn string) (name string, date time.Time, err error) {
	if len(fn) < 12 {
		err = ErrBadPostName
		return
	}
	date, err = time.Parse("2006-01-02", fn[:10])
	if err != nil {
		return
	}
	name = fn[11:]
	name = removeExt(name)

	name = strings.Replace(name, "-", " ", -1)
	name = strings.ToTitle(name)
	return
}
コード例 #26
0
ファイル: http_tamperer.go プロジェクト: roger2000hk/muxy
func (m *HttpTampererSymptom) MuckResponse(ctx *muxy.Context) {

	// Body
	if m.Response.Body != "" {
		var cl io.ReadCloser
		cl = &responseBody{body: []byte(m.Response.Body)}
		r := &http.Response{
			Request:          ctx.Request,
			Header:           ctx.Response.Header,
			Close:            ctx.Response.Close,
			ContentLength:    ctx.Response.ContentLength,
			Trailer:          ctx.Response.Trailer,
			TLS:              ctx.Response.TLS,
			TransferEncoding: ctx.Response.TransferEncoding,
			Status:           ctx.Response.Status,
			StatusCode:       ctx.Response.StatusCode,
			Proto:            ctx.Response.Proto,
			ProtoMajor:       ctx.Response.ProtoMajor,
			ProtoMinor:       ctx.Response.ProtoMinor,
			Body:             cl,
		}
		log.Debug("Injecting HTTP Response Body with %s", log.Colorize(log.BLUE, m.Response.Body))
		*ctx.Response = *r
	}

	// Set Cookies
	for _, c := range m.Response.Cookies {
		c.Expires = stringToDate(c.RawExpires)
		log.Debug("Spoofing Response Cookie %s => %s", log.Colorize(log.LIGHTMAGENTA, c.Name), c.String())
		ctx.Response.Header.Add("Set-Cookie", c.String())
	}

	// Set Headers
	for k, v := range m.Response.Headers {
		key := strings.ToTitle(strings.Replace(k, "_", "-", -1))
		log.Debug("Spoofing Response Header %s => %s", log.Colorize(log.LIGHTMAGENTA, key), v)
		ctx.Response.Header.Add(key, v)
	}

	// This Writes all headers, setting status code - so call this last
	if m.Response.Status != 0 {
		ctx.Response.StatusCode = m.Response.Status
		ctx.Response.Status = http.StatusText(m.Response.Status)
	}
}
コード例 #27
0
ファイル: http_tamperer.go プロジェクト: read-later/muxy
func (m *HttpTampererSymptom) HandleEvent(e muxy.ProxyEvent, ctx *muxy.Context) {
	switch e {
	case muxy.EVENT_POST_DISPATCH:
		log.Debug("Spoofing status code, responding with %s", log.Colorize(log.YELLOW, fmt.Sprintf("%d %s", m.Status, http.StatusText(m.Status))))

		// Body
		if m.Body != "" {
			var cl io.ReadCloser
			cl = &responseBody{body: []byte(m.Body)}
			r := &http.Response{
				Request:          ctx.Request,
				Header:           ctx.Response.Header,
				Close:            ctx.Response.Close,
				ContentLength:    ctx.Response.ContentLength,
				Trailer:          ctx.Response.Trailer,
				TLS:              ctx.Response.TLS,
				TransferEncoding: ctx.Response.TransferEncoding,
				Status:           ctx.Response.Status,
				StatusCode:       ctx.Response.StatusCode,
				Proto:            ctx.Response.Proto,
				ProtoMajor:       ctx.Response.ProtoMajor,
				ProtoMinor:       ctx.Response.ProtoMinor,
				Body:             cl,
			}
			log.Debug("Injecting HTTP Response Body with %s", log.Colorize(log.BLUE, m.Body))
			*ctx.Response = *r
		}

		// Set Headers
		for k, v := range m.Headers {
			key := strings.ToTitle(strings.Replace(k, "_", "-", -1))
			log.Debug("Spoofing Header %s => %s", log.Colorize(log.LIGHTMAGENTA, key), v)
			ctx.Response.Header.Add(key, v)
			ctx.ResponseWriter.Header().Add(key, v)
		}

		// This Writes all headers, setting status code - so call this last
		ctx.Response.StatusCode = m.Status
		ctx.Response.Status = http.StatusText(m.Status)
		ctx.ResponseWriter.WriteHeader(m.Status)
	}
}
コード例 #28
0
ファイル: auth.go プロジェクト: janiukjf/SiteMonitor
func Index(w http.ResponseWriter, r *http.Request) {
	var err error
	var tmpl plate.Template

	params := r.URL.Query()
	error := params.Get(":error")
	error, _ = url.QueryUnescape(error)
	server := plate.NewServer()

	tmpl, err = server.Template(w)

	if err != nil {
		plate.Serve404(w, err.Error())
		return
	}

	tmpl.Bag["Error"] = strings.ToTitle(error)
	tmpl.Template = "templates/auth/in.html"
	tmpl.DisplayTemplate()
}
コード例 #29
0
ファイル: softcode.go プロジェクト: natmeox/mess
func MessThingPronounsubMethod(state *lua.State, thing *Thing) int {
	state.PushGoFunction(func(state *lua.State) int {
		thing := checkThing(state, 1)
		text := state.CheckString(2)

		for code, pronoun := range thing.Pronouns() {
			lowerCode := fmt.Sprintf(`%%%s`, code)
			upperCode := fmt.Sprintf(`%%%s`, strings.ToUpper(code))
			text = strings.Replace(text, lowerCode, pronoun, -1)
			text = strings.Replace(text, upperCode, strings.ToTitle(pronoun), -1)
		}

		text = strings.Replace(text, `%n`, thing.Name, -1)
		text = strings.Replace(text, `%N`, thing.Name, -1)

		state.Pop(2)           // ( udataThing str -- )
		state.PushString(text) // ( -- str' )
		return 1
	})
	return 1
}
コード例 #30
0
ファイル: handlers.go プロジェクト: jfrazelle/snippetlib
func (h *Handler) renderTemplate(w http.ResponseWriter, r *http.Request, category, slug string) {
	page, err := query(h.dbConn, category, slug)
	if err != nil {
		writeError(w, r, err.Error())
		return
	}
	page.URL = r.URL.String()

	if slug == "" && len(page.Snippets) == 0 {
		writeError(w, r, fmt.Sprintf("no snippets found for category (%s)", category))
		return
	}

	// render the template
	lp := path.Join(templateDir, "layout.html")

	// set up custom functions
	funcMap := template.FuncMap{
		"stripSlashes": func(s string) string {
			return strings.Replace(s, "/", "", -1)
		},
		"stripTags": func(s string) string {
			reHTML := regexp.MustCompile(`<.+>`)
			return reHTML.ReplaceAllString(s, "")
		},
		"toTitle": func(s string) string {
			return strings.ToTitle(s)
		},
		"toUppercase": func(s string) string {
			return strings.ToUpper(s)
		},
	}

	// parse & execute the template
	tmpl := template.Must(template.New("").Funcs(funcMap).ParseFiles(lp))
	if err := tmpl.ExecuteTemplate(w, "layout", page); err != nil {
		writeError(w, r, fmt.Sprintf("execute template failed: %v", err))
		return
	}
}