Golang Title示例

说明

golang title示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: strings

示例#1
文件: structGenerator.go 项目: knutsel/GoTO

//writes structInterface.go, which has a function that takes in *Rows,
//makes them into an array of []TableName structs, and encodes this
//array into JSON format
func MakeStructInterface() {
	//header, imports
	structInterface := "package structs\n"
	structInterface += "import (\n"
	structInterface += "\t\"github.com/jmoiron/sqlx\"\n"
	structInterface += "\t\"encoding/json\"\n"
	structInterface += "\t\"net/http\"\n"
	structInterface += ")\n"

	//makes a function for each object
	tableList := sqlParser.GetTableNames()
	for _, table := range tableList {
		//function declaration
		structInterface += "func EncodeStruct" + strings.Title(table) + "(rows *sqlx.Rows, w http.ResponseWriter) {\n" //make new array
		structInterface += "\tsa := make([]" + strings.Title(table) + ", 0)\n"
		//make new instance
		structInterface += "\tt := " + strings.Title(table) + "{}\n\n"
		//loops through all columns and translates to JSON
		structInterface += "\tfor rows.Next() {\n"
		structInterface += "\t\t rows.StructScan(&t)\n"
		structInterface += "\t\t sa = append(sa, t)\n"
		structInterface += "\t}\n\n"
		structInterface += "\tenc := json.NewEncoder(w)\n"
		structInterface += "\tenc.Encode(sa)\n"
		structInterface += "}\n"
	}

	//writes in relation to home directory
	structBuilder.WriteFile(structInterface, "./structs/structInterface.go")
}

示例#2
文件: contest.go 项目: netyum/GoOnlineJudge

func (this *ContestController) List(w http.ResponseWriter, r *http.Request) {
	class.Logger.Debug("Contest List")
	this.Init(w, r)

	args := this.ParseURL(r.URL.String())

	Type := args["type"]
	CModel := model.ContestModel{}
	conetestList, err := CModel.List(args)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	this.Data["Contest"] = conetestList
	this.Data["Time"] = this.GetTime()
	this.Data["Type"] = Type
	this.Data["Title"] = strings.Title(Type) + " List"
	this.Data["Is"+strings.Title(Type)] = true
	this.Data["Privilege"] = this.Privilege
	err = this.Execute(w, "view/layout.tpl", "view/contest_list.tpl")
	if err != nil {
		class.Logger.Debug(err)
		http.Error(w, "tpl error", 500)
		return
	}
}

示例#3
文件: main.go 项目: mesosphere/dcos-kafka-service

func main() {
	modName, err := cli.GetModuleName()
	if err != nil {
		log.Fatalf(err.Error())
	}

	app, err := cli.NewApp(
		"0.1.0",
		"Mesosphere",
		fmt.Sprintf("Deploy and manage %s clusters", strings.Title(modName)))
	if err != nil {
		log.Fatalf(err.Error())
	}

	handleBrokerSection(app)
	handleTopicSection(app)
	cli.HandleCommonArgs(
		app,
		modName,
		fmt.Sprintf("%s DC/OS CLI Module", strings.Title(modName)),
		[]string{"address", "dns"})

	// Omit modname:
	kingpin.MustParse(app.Parse(os.Args[2:]))
}

示例#4
文件: resourceful.go 项目: jflinter/Resourceful

func parseFolder(filepath string) (EnumType, error) {
	files, err := ioutil.ReadDir(filepath)
	if err != nil {
		return EnumType{}, err
	}
	enumCases := []EnumCase{}
	enumTypes := []EnumType{}
	for _, f := range files {
		if strings.HasSuffix(f.Name(), "imageset") {
			rawValue := strings.Split(f.Name(), ".")[0]
			name := strings.Title(rawValue)
			name = strings.Replace(name, "_", "__", -1)
			name = strings.Replace(name, "-", "_", -1)
			enum := EnumCase{name, rawValue}
			enumCases = append(enumCases, enum)
		} else if !strings.Contains(f.Name(), ".") {
			folderName := path.Join(filepath, f.Name())
			enumType, err := parseFolder(folderName)
			if err != nil {
				return EnumType{}, err
			}
			enumTypes = append(enumTypes, enumType)
		}
	}
	_, file := path.Split(filepath)
	name := strings.Title(file)
	return EnumType{name, enumCases, enumTypes}, nil
}

示例#5
文件: generators.go 项目: alistanis/stg

func generateWhere(t *models.Table, adapter string) (string, error) {
	placeholder := getPlaceholder(adapter)
	title := strings.Title(t.Name)
	firstChar := strings.ToLower(string(t.Name[0]))
	funcPlaceholderText := FormatFunction(title, "Where", "column string, arg interface{}", fmt.Sprintf("([]*%s, error)", title))
	queryText := `"select * from %s where %s = %s;"`
	if placeholder == "?" {
		queryText = fmt.Sprintf(queryText, t.Name, placeholder, placeholder)
	} else {
		queryText = fmt.Sprintf(queryText, t.Name, placeholder, "$2")
	}
	typeName := inflector.Singularize(strings.Title(t.Name))
	srcText := fmt.Sprintf(`	%s := make([]*%s, 0)
	rows, err := db.Queryx(%s, column, arg)
	if err != nil {
		return "", err
	}
	for rows.Next() {
			%s := &%s{}
			err = rows.StructScan(%s)
			if err != nil {
				return nil, err
			}
			%s = append(%s, %s)
		}
	return %s, nil`, firstChar+"s", typeName, queryText, firstChar, typeName, firstChar, firstChar+"s", firstChar+"s", firstChar, firstChar+"s")

	functionText := fmt.Sprintf(funcPlaceholderText, srcText)
	return functionText, nil
}

示例#6
文件: main.go 项目: gitter-badger/hypermusk

func printjava(dir string, apiset *parser.APISet, javapackage string) {
	if javapackage == "" {
		die(errors.New("must use -java_package=com.qortex.android to give java package"))
	}

	filedir := filepath.Join(dir, strings.Replace(javapackage, ".", "/", -1))
	err1 := os.MkdirAll(filedir, 0755)
	dieIf(err1)
	tpl := codeTemplate()

	for _, dataobj := range apiset.DataObjects {
		writeSingleJavaFile(tpl, filedir, javapackage, "java/dataobject", dataobj.Name, dataobj)
	}

	for _, inf := range apiset.Interfaces {
		data := make(map[string]interface{})
		data["Prefix"] = apiset.Prefix
		data["Interface"] = inf
		data["PkgName"] = strings.Title(apiset.Name)
		writeSingleJavaFile(tpl, filedir, javapackage, "java/interface", inf.Name, data)
	}
	writeSingleJavaFile(tpl, filedir, javapackage, "java/remote_error", "RemoteError", nil)
	writeSingleJavaFile(tpl, filedir, javapackage, "java/base64", "Base64", nil)

	writeSingleJavaFile(tpl, filedir, javapackage, "java/packageclass", strings.Title(apiset.Name), apiset)
}

示例#7
文件: capnpc-pgo.go 项目: tpukep/caps

func (n *node) resolveName(base, name string, file *node) {
	if na := nameAnnotation(n.Annotations()); na != "" {
		name = na
	}
	if base != "" {
		n.name = base + strings.Title(name)
	} else {
		n.name = strings.Title(name)
	}

	n.pkg = file.pkg
	n.imp = file.imp

	if n.Which() != caps.NODE_STRUCT || !n.Struct().IsGroup() {
		file.nodes = append(file.nodes, n)
	}

	for _, nn := range n.NestedNodes().ToArray() {
		if ni := g_nodes[nn.Id()]; ni != nil {
			ni.resolveName(n.name, nn.Name(), file)
		}
	}

	if n.Which() == caps.NODE_STRUCT {
		for _, f := range n.Struct().Fields().ToArray() {
			if f.Which() == caps.FIELD_GROUP {
				gname := f.Name()
				if na := nameAnnotation(f.Annotations()); na != "" {
					gname = na
				}
				findNode(f.Group().TypeId()).resolveName(n.name, gname, file)
			}
		}
	}
}

示例#8
文件: method.go 项目: Jumpscale/go-raml

// format Nim proc name from complete URI
func formatProcName(fullURI string) string {
	// remove leading `/`
	fullURI = fullURI[1:]

	// When meet `/{`
	// - replace it with `By`
	// - make uppercase the first char after `/{`
	spl := strings.Split(fullURI, "/{")
	tmp := []string{}
	for i, v := range spl {
		if i != 0 {
			v = strings.Title(v)
		}
		tmp = append(tmp, v)
	}
	name := strings.Join(tmp, "By")

	// when meet `/`
	// - make uppercase the first char after `/`
	// - remove the `/`
	spl = strings.Split(name, "/")
	tmp = []string{}
	for i, v := range spl {
		if i != 0 {
			v = strings.Title(v)
		}
		tmp = append(tmp, v)
	}

	return strings.Join(tmp, "")
}

示例#9
文件: codegen.go 项目: gsrpc/gsrpc

func exception(name string) string {
	if strings.HasSuffix(name, "Exception") {
		return strings.Title(name)
	}

	return strings.Title(name) + "Exception"
}

示例#10
文件: route.go 项目: yylover/programe

func adminHandler(w http.ResponseWriter, r *http.Request) {
	//权限判断
	cookie, err := r.Cookie("admin_name")
	if err != nil || cookie.Value == "" {
		http.Redirect(w, r, "/login/index", http.StatusFound)
	}

	//路由
	pathInfo := strings.Trim(r.URL.Path, "/")
	parts := strings.Split(pathInfo, "/")
	var action = ""
	if len(parts) > 1 {
		action = strings.Title(parts[1]) + "Action"
	}

	fmt.Printf("path%s %v\n", "adminHandler", pathInfo)
	login := &controller.AdminController{}
	controller := reflect.ValueOf(login)
	method := controller.MethodByName(action)
	if !method.IsValid() {
		method = controller.MethodByName(strings.Title("index") + "Action")
	}
	requestValue := reflect.ValueOf(r)
	responseValue := reflect.ValueOf(w)
	method.Call([]reflect.Value{responseValue, requestValue})

}

示例#11
文件: body_input.go 项目: mouse225/qt

func IsPrivateSignal(f *parser.Function) bool {

	var fData string

	switch runtime.GOOS {
	case "darwin":
		fData = utils.Load(fmt.Sprintf("/usr/local/Qt5.5.1/5.5/clang_64/lib/%v.framework/Versions/5/Headers/%v", strings.Title(parser.ClassMap[f.Class()].DocModule), filepath.Base(f.Filepath)))

	case "windows":
		fData = utils.Load(fmt.Sprintf("C:\\Qt\\Qt5.5.1\\5.5\\mingw492_32\\include\\%v\\%v", strings.Title(parser.ClassMap[f.Class()].DocModule), filepath.Base(f.Filepath)))

	case "linux":
		switch runtime.GOARCH {
		case "amd64":
			{
				fData = utils.Load(fmt.Sprintf("/usr/local/Qt5.5.1/5.5/gcc_64/include/%v/%v", strings.Title(parser.ClassMap[f.Class()].DocModule), filepath.Base(f.Filepath)))
			}
		case "386":
			{
				fData = utils.Load(fmt.Sprintf("/usr/local/Qt5.5.1/5.5/gcc/include/%v/%v", strings.Title(parser.ClassMap[f.Class()].DocModule), filepath.Base(f.Filepath)))
			}
		}
	}

	if fData != "" {
		return strings.Contains(strings.Split(strings.Split(fData, f.Name+"(")[1], ")")[0], "QPrivateSignal")
	} else {
		fmt.Println("converter.IsPrivateSignal", f.Class())
	}

	return false
}

示例#12
文件: models.go 项目: cweill/gotests

func (f *Function) FullName() string {
	var r string
	if f.Receiver != nil {
		r = f.Receiver.Type.Value
	}
	return strings.Title(r) + strings.Title(f.Name)
}

示例#13
文件: docker.go 项目: y-kuno/mackerel-agent-plugins

func (m DockerPlugin) parseStats(stats *map[string]interface{}, name string, result *docker.Stats) error {
	(*stats)["docker.cpuacct."+name+".user"] = (*result).CPUStats.CPUUsage.UsageInUsermode
	(*stats)["docker.cpuacct."+name+".system"] = (*result).CPUStats.CPUUsage.UsageInKernelmode
	(*stats)["docker.memory."+name+".cache"] = (*result).MemoryStats.Stats.TotalCache
	(*stats)["docker.memory."+name+".rss"] = (*result).MemoryStats.Stats.TotalRss
	fields := []string{"read", "write", "sync", "async"}
	for _, field := range fields {
		for _, s := range (*result).BlkioStats.IOQueueRecursive {
			if s.Op == strings.Title(field) {
				(*stats)["docker.blkio.io_queued."+name+"."+field] = s.Value
			}
		}
		for _, s := range (*result).BlkioStats.IOServicedRecursive {
			if s.Op == strings.Title(field) {
				(*stats)["docker.blkio.io_serviced."+name+"."+field] = s.Value
			}
		}
		for _, s := range (*result).BlkioStats.IOServiceBytesRecursive {
			if s.Op == strings.Title(field) {
				(*stats)["docker.blkio.io_service_bytes."+name+"."+field] = s.Value
			}
		}
	}
	return nil
}

示例#14
文件: issue5162.go 项目: 2thetop/go

func main() {
	fmt.Print("// run\n\n")
	fmt.Print("// THIS FILE IS AUTO-GENERATED\n\n")
	fmt.Print("package main\n\n")
	fmt.Println(`import "fmt"`)

	types := []string{
		"int", "int8", "int16", "int32", "int64",
		"uint", "uint8", "uint16", "uint32", "uint64",
		"float32", "float64"}
	tocall := make([]string, 0, 32*len(types))
	for i := 1; i <= 32; i++ {
		for _, typ := range types {
			src := template
			src = strings.Replace(src, "NNN", fmt.Sprint(i), -1)
			src = strings.Replace(src, "TTT", strings.Title(typ), -1)
			src = strings.Replace(src, "ttt", typ, -1)
			src = strings.Replace(src, "ONES", "1"+strings.Repeat(", 1", i-1), -1)
			src = strings.Replace(src, "TWOS", "2"+strings.Repeat(", 2", i-1), -1)
			fmt.Print(src)
			tocall = append(tocall, fmt.Sprintf("CheckEq%d_%s", i, strings.Title(typ)))
		}
	}
	fmt.Println("func main() {")
	for _, fun := range tocall {
		fmt.Printf("\t%s()\n", fun)
		fmt.Printf("\t%sExtraVar()\n", fun)
	}
	fmt.Println("}")
}

示例#15
文件: jsonToGo.go 项目: mingderwang/pepper

func Gen(jsonStream string, typeName string) (string, error) {
	typeBody := header + "type "
	typeBody = typeBody + strings.Title(typeName) + " struct {"
	typeBody = typeBody + footer + fmt.Sprintf("\n")
	typeBody = typeBody + fmt.Sprintf("\n")
	dec := json.NewDecoder(strings.NewReader(jsonStream))
	status := InitStatus
	tmp := ""
	type2 := ""
	for {
		t, err := dec.Token()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
			return "", err
		}
		tmp = fmt.Sprintf("%v", t)
		if fmt.Sprintf("%T", t) == "string" && status == InitStatus {
			typeBody = typeBody + fmt.Sprintf("\t") +
				strings.Title(tmp) + " "
			status = WaitStatus
			type2 = tmp
		} else if status == WaitStatus {
			typeBody = typeBody + fmt.Sprintf("%T", t) + " `json:\"" + type2 + "\"`" + fmt.Sprintf("\n")
			status = InitStatus
		}
	}
	typeBody = typeBody + "}"
	return typeBody, nil
}

示例#16
文件: contest.go 项目: netyum/GoOnlineJudge

//列出所有的比赛 url:/admin/contest/list/type/<contest,exercise>
func (this *ContestController) List(w http.ResponseWriter, r *http.Request) {
	class.Logger.Debug("Contest List")
	this.Init(w, r)

	args := this.ParseURL(r.URL.String())
	Type := args["type"]

	qry := make(map[string]string)
	qry["type"] = Type
	contestModel := model.ContestModel{}
	contestList, err := contestModel.List(args)
	if err != nil {
		http.Error(w, err.Error(), 400)
	}

	this.Data["Contest"] = contestList
	this.Data["Title"] = "Admin - " + strings.Title(Type) + " List"
	this.Data["Is"+strings.Title(Type)] = true
	this.Data["IsList"] = true
	err = this.Execute(w, "view/admin/layout.tpl", "view/admin/contest_list.tpl")
	if err != nil {
		http.Error(w, "tpl error", 500)
		return
	}

}

示例#17
文件: forms.go 项目: scottcagno/net_kit

func (self *Form) IsValid(r *http.Request) bool {
	isValid := true
	for i := 0; i < len(self.Inputs); i++ {
		formVal := r.FormValue(self.Inputs[i].Name)
		if self.Inputs[i].Required {
			//formVal := r.FormValue(self.Inputs[i].Name)
			if len(formVal) < 1 {
				err := fmt.Sprintf("*%s is a required field", strings.Title(self.Inputs[i].Name))
				self.Inputs[i].Error = err
				self.Errors[self.Inputs[i].Name] = err
				isValid = false
				//break
			} else {
				self.Inputs[i].Value = formVal
			}
			switch self.Inputs[i].Type {
			case "email":
				if !strings.Contains(formVal, "@") {
					err := "*Email field requires an email address"
					self.Inputs[i].Error = err
					self.Errors[self.Inputs[i].Name] = err
					isValid = false
					//break
				} else {
					self.Inputs[i].Value = formVal
				}
			case "password":
				if self.Inputs[i].Min != 0 && len(formVal) < self.Inputs[i].Min {
					err := fmt.Sprintf("*Password minimum is %d", self.Inputs[i].Min)
					self.Inputs[i].Error = err
					self.Errors[self.Inputs[i].Name] = err
					isValid = false
					//break
				} else {
					self.Inputs[i].Value = formVal
				}
				if self.Inputs[i].Max != 0 && self.Inputs[i].Max > self.Inputs[i].Min && len(formVal) > self.Inputs[i].Max {
					err := fmt.Sprintf("*Password maximum is %d", self.Inputs[i].Max)
					self.Inputs[i].Error = err
					self.Errors[self.Inputs[i].Name] = err
					isValid = false
					//break
				} else {
					self.Inputs[i].Value = formVal
				}
			case "number":
				if !isNumber(formVal) {
					err := fmt.Sprintf("*%s requires a number", strings.Title(self.Inputs[i].Name))
					self.Inputs[i].Error = err
					self.Errors[self.Inputs[i].Name] = err
					isValid = false
					//break
				} else {
					self.Inputs[i].Value = formVal
				}
			}
		}
	}
	return isValid
}

示例#18
文件: command_push.go 项目: uetchy/magicformula

func toCamelCase(str string) string {
	re, _ := regexp.Compile("[_-](.)")
	res := re.ReplaceAllStringFunc(str, func(j string) string {
		return strings.Title(j[1:])
	})
	return strings.Title(res)
}

示例#19
文件: api.go 项目: micro/micro

// Translates /foo/bar/zool into api service go.micro.api.foo method Bar.Zool
// Translates /foo/bar into api service go.micro.api.foo method Foo.Bar
func pathToReceiver(ns, p string) (string, string) {
	p = path.Clean(p)
	p = strings.TrimPrefix(p, "/")
	parts := strings.Split(p, "/")

	// If we've got two or less parts
	// Use first part as service
	// Use all parts as method
	if len(parts) <= 2 {
		service := ns + "." + strings.Join(parts[:len(parts)-1], ".")
		method := strings.Title(strings.Join(parts, "."))
		return service, method
	}

	// Treat /v[0-9]+ as versioning where we have 3 parts
	// /v1/foo/bar => service: v1.foo method: Foo.bar
	if len(parts) == 3 && versionRe.Match([]byte(parts[0])) {
		service := ns + "." + strings.Join(parts[:len(parts)-1], ".")
		method := strings.Title(strings.Join(parts[len(parts)-2:], "."))
		return service, method
	}

	// Service is everything minus last two parts
	// Method is the last two parts
	service := ns + "." + strings.Join(parts[:len(parts)-2], ".")
	method := strings.Title(strings.Join(parts[len(parts)-2:], "."))
	return service, method
}

示例#20
文件: input.go 项目: andradeandrey/obsidian

func ReadPost(content string, path string) *Post {
	groups := strings.Split(content, "\n\n", 2)
	metalines := strings.Split(groups[0], "\n", -1)
	post := &Post{}
	post.Content, _ = markdown.Format(groups[1])
	post.Title = metalines[0]
	post.Meta = make(map[string]interface{})
	for _, line := range metalines[1:] { // TODO move to package config
		ind := strings.Index(line, ":")
		if ind != -1 {
			key, value := line[0:ind], strings.TrimSpace(line[ind+1:])
			post.Meta[strings.Title(key)] = value

			// and as a list
			post.Meta[strings.Title(key)+"List"] = asList(value)
		}
	}
	post.URL = path

	// clean the post
	if len(post.Meta["Category"].(string)) == 0 {
		post.Category = "General" // TODO make this configurable
	} else {
		post.Category = post.Meta["Category"].(string)
	}
	return post
}

示例#21
文件: controller.go 项目: dej4vu/figo

func autoRouteFunc(this ControllerInterface, httpMethod, path string) {
	comps := toolkit.SplitString(path, "/")
	if len(comps) < 2 {
		this.HandleRequestPathNotFound()
		return
	}
	var methodName string
	for _, v := range comps[1:] {
		subComps := strings.Split(v, "-")
		for _, vv := range subComps {
			methodName += strings.Title(vv)
		}
	}
	if len(methodName) == 0 {
		this.HandleRequestPathNotFound()
		return
	}
	methodName = strings.Title(strings.ToLower(httpMethod)) + methodName
	value := reflect.ValueOf(this)
	method := value.MethodByName(methodName)
	if !method.IsValid() {
		this.HandleRequestPathNotFound()
		return
	}
	method.Call(nil)
}

示例#22
文件: admin-m.go 项目: Laller/hypecms

// Install and Uninstall hooks all have the same signature: func (a *A)(bson.ObjectId) error
// InstallB handles both installing and uninstalling.
func InstallB(uni *context.Uni, mode string) error {
	if !requireLev(uni.Dat["_user"], 300) {
		return fmt.Errorf("No rights to install or uninstall a module.")
	}
	dat, err := extract.New(map[string]interface{}{"module": "must"}).Extract(uni.Req.Form)
	if err != nil {
		return err
	}
	modn := dat["module"].(string)
	uni.Dat["_cont"] = map[string]interface{}{"module": modn}
	obj_id, ierr := admin_model.InstallB(uni.Db, uni.Ev, uni.Opt, modn, mode)
	if ierr != nil {
		return ierr
	}
	if !uni.Caller.Has("hooks", modn, strings.Title(mode)) {
		return fmt.Errorf("Module %v does not export the Hook %v.", modn, mode)
	}
	//hook, ok := h.(func(*context.Uni, bson.ObjectId) error)
	//if !ok {
	//	return fmt.Errorf("%v hook of module %v has bad signature.", mode, modn)
	//}
	ret_rec := func(e error) {
		err = e
	}
	uni.Caller.Call("hooks", modn, strings.Title(mode), ret_rec, obj_id)
	return err
}

示例#23
文件: site.go 项目: johnsto/hugo

// Render a page for each section
func (s *Site) RenderSectionLists() error {
	for section, data := range s.Sections {
		n := s.NewNode()
		if viper.GetBool("PluralizeListTitles") {
			n.Title = strings.Title(inflect.Pluralize(section))
		} else {
			n.Title = strings.Title(section)
		}
		s.setUrls(n, section)
		n.Date = data[0].Page.Date
		n.Data["Pages"] = data.Pages()
		layouts := []string{"section/" + section + ".html", "_default/section.html", "_default/list.html", "indexes/" + section + ".html", "_default/indexes.html"}

		err := s.render(n, section, s.appendThemeTemplates(layouts)...)
		if err != nil {
			return err
		}

		if !viper.GetBool("DisableRSS") {
			// XML Feed
			rssLayouts := []string{"section/" + section + ".rss.xml", "_default/rss.xml", "rss.xml", "_internal/_default/rss.xml"}
			s.setUrls(n, section+".xml")
			err = s.render(n, section+".xml", s.appendThemeTemplates(rssLayouts)...)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

示例#24
文件: main.go 项目: hemaolong/Rabbit

func adminHandler(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie("admin_name")
	if err != nil && cookie.Value == "" {
		http.Redirect(w, r, "/login/index", http.StatusNotFound)

		pathInfo := strings.Trim(r.URL.Path, "/")
		parts := strings.Split(pathInfo, "/")

		action := ""
		if len(parts) > 1 {
			action = strings.Title(parts[1]) + "Action"
		}

		admin := &adminController{}
		controller := reflect.ValueOf(admin)
		method := controller.MethodByName(action)
		if !method.IsValid() {
			method = controller.MethodByName(strings.Title("index") + "Action")
		}
		requestValue := reflect.ValueOf(r)
		responseValue := reflect.ValueOf(w)
		userValue := reflect.ValueOf(cookie.Value)
		method.Call([]reflect.Value{responseValue, requestValue, userValue})

	}
}

示例#25
文件: vmvultr.go 项目: nhocconan/lobster

func (this *Vultr) VmInfo(vm *lobster.VirtualMachine) (*lobster.VmInfo, error) {
	server, err := this.client.GetServer(vm.Identification)
	if err != nil {
		return nil, err
	}

	info := lobster.VmInfo{
		Ip:            server.MainIP,
		PrivateIp:     server.InternalIP,
		Hostname:      server.Name,
		BandwidthUsed: int64(server.CurrentBandwidth * 1024 * 1024 * 1024),
		LoginDetails:  "password: " + server.DefaultPassword,
	}

	if server.Status == "pending" {
		info.Status = "Installing"
	} else if server.Status == "active" {
		if server.PowerStatus == "stopped" {
			info.Status = "Offline"
		} else if server.PowerStatus == "running" {
			info.Status = "Online"
		} else {
			info.Status = server.PowerStatus
		}
	} else {
		info.Status = fmt.Sprintf("%s (%s)", strings.Title(server.Status), strings.Title(server.PowerStatus))
	}

	return &info, nil
}

示例#26
文件: model_generator.go 项目: sparkymat/clay

func (g *ModelGenerator) Write(writer io.Writer, t typewriter.Type) error {
	tag, found := t.FindTag(g)

	if !found {
		return nil
	}

	// Fetch core template
	coreTemplates := templates.Where(func(t *typewriter.Template) bool {
		if t != nil && t.Name == "core" {
			return true
		}

		return false
	})
	if len(coreTemplates) == 0 {
		return errors.New("Unable to find 'core' template")
	}
	coreTemplate, err := coreTemplates[0].Parse()
	if err != nil {
		return errors.New("Unable to parse 'core' template")
	}

	// Fetch relation template
	relationTemplates := templates.Where(func(t *typewriter.Template) bool {
		if t != nil && t.Name == "relation" {
			return true
		}

		return false
	})
	if len(relationTemplates) == 0 {
		return errors.New("Unable to find 'relation' template")
	}
	relationTemplate, err := relationTemplates[0].Parse()
	if err != nil {
		return errors.New("Unable to parse 'relation' template")
	}

	cValues := coreValues{ModelClassName: t.Name}
	if err := coreTemplate.Execute(writer, cValues); err != nil {
		return err
	}

	for _, relation := range tag.Values {
		templateValues := relationValues{}

		templateValues.ModelClassName = t.Name
		templateValues.RelationIdentifierName = fmt.Sprintf("%vIdentifier", strings.Title(relation.Name))
		templateValues.RelationName = relation.Name
		templateValues.RelationClassName = strings.Title(relation.Name)

		if err := relationTemplate.Execute(writer, templateValues); err != nil {
			return err
		}
	}

	return nil
}

示例#27
文件: input.go 项目: xland/qt

func goInput(name string, value string, f *parser.Function) string {
	var vOld = value

	name = cleanName(name)
	value = cleanValue(value)

	switch value {
	case "QStringList":
		{
			return fmt.Sprintf("C.CString(strings.Join(%v, \"|\"))", name)
		}

	case "uchar", "char", "QString":
		{
			if strings.Contains(vOld, "**") {
				return fmt.Sprintf("C.CString(strings.Join(%v, \"|\"))", name)
			}
			return fmt.Sprintf("C.CString(%v)", name)
		}

	case "bool":
		{
			return fmt.Sprintf("C.int(qt.GoBoolToInt(%v))", name)
		}

	case "int":
		{
			return fmt.Sprintf("C.int(%v)", name)
		}

	case "qreal":
		{
			return fmt.Sprintf("C.double(%v)", name)
		}

	case "jclass":
		{
			return name
		}
	}

	switch {
	case isEnum(f.Class(), value):
		{
			return fmt.Sprintf("C.int(%v)", name)
		}

	case isClass(value):
		{
			if m := module(parser.ClassMap[value].Module); m != module(f) {
				return fmt.Sprintf("%v.PointerFrom%v(%v)", m, strings.Title(value), name)
			}
			return fmt.Sprintf("PointerFrom%v(%v)", strings.Title(value), name)
		}
	}

	f.Access = "unsupported_goInput"
	return f.Access
}

示例#28
文件: name.go 项目: WaylandGod/go-start

func (self *Name) SetForPerson(prefix, first, middle, last, postfix string) {
	self.Prefix.Set(prefix)
	self.First.Set(strings.Title(strings.ToLower(first)))
	self.Middle.Set(strings.Title(strings.ToLower(middle)))
	self.Last.Set(strings.Title(strings.ToLower(last)))
	self.Postfix.Set(postfix)
	self.Organization = ""
}

示例#29
文件: ios.go 项目: ksoichiro/mocker

func genIosViewController(mock *Mock, dir string, screen Screen, layoutCodeBuf *CodeBuffer) {
	var buf CodeBuffer
	genCodeIosViewControllerHeader(mock, screen, &buf)
	genFile(&buf, filepath.Join(dir, mock.Meta.Ios.Project, mock.Meta.Ios.ClassPrefix+strings.Title(screen.Id)+"ViewController.h"))
	buf = CodeBuffer{}
	genCodeIosViewControllerImplementation(mock, screen, &buf, layoutCodeBuf)
	genFile(&buf, filepath.Join(dir, mock.Meta.Ios.Project, mock.Meta.Ios.ClassPrefix+strings.Title(screen.Id)+"ViewController.m"))
}

示例#30
文件: scanner_test.go 项目: jason-xxl/go-swagger

func verifyBoolean(t *testing.T, matcher *regexp.Regexp, names, names2 []string) {
	extraSpaces := []string{"", " ", "  ", "     "}
	prefixes := []string{"//", "*", ""}
	validArgs := []string{"true", "false"}
	invalidArgs := []string{"TRUE", "FALSE", "t", "f", "1", "0", "True", "False", "true*", "false*"}
	var nms []string
	for _, nm := range names {
		nms = append(nms, nm, strings.Title(nm))
	}

	var nms2 []string
	for _, nm := range names2 {
		nms2 = append(nms2, nm, strings.Title(nm))
	}

	var rnms []string
	if len(nms2) > 0 {
		for _, nm := range nms {
			for _, es := range append(extraSpaces, "-") {
				for _, nm2 := range nms2 {
					rnms = append(rnms, strings.Join([]string{nm, es, nm2}, ""))
				}
			}
		}
	} else {
		rnms = nms
	}

	var cnt int
	for _, pref := range prefixes {
		for _, es1 := range extraSpaces {
			for _, nm := range rnms {
				for _, es2 := range extraSpaces {
					for _, es3 := range extraSpaces {
						for _, vv := range validArgs {
							line := strings.Join([]string{pref, es1, nm, es2, ":", es3, vv}, "")
							matches := matcher.FindStringSubmatch(line)
							assert.Len(t, matches, 2)
							assert.Equal(t, vv, matches[1])
							cnt++
						}
						for _, iv := range invalidArgs {
							line := strings.Join([]string{pref, es1, nm, es2, ":", es3, iv}, "")
							matches := matcher.FindStringSubmatch(line)
							assert.Empty(t, matches)
							cnt++
						}
					}
				}
			}
		}
	}
	var nm2 string
	if len(names2) > 0 {
		nm2 = " " + names2[0]
	}
	fmt.Printf("tested %d %s%s combinations\n", cnt, names[0], nm2)
}

展开阅读全文