本文整理汇总了Golang中html/template.URL函数的典型用法代码示例。如果您正苦于以下问题:Golang URL函数的具体用法?Golang URL怎么用?Golang URL使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了URL函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ReverseUrl
// Return a url capable of invoking a given controller method:
// "Application.ShowApp 123" => "/app/123"
func ReverseUrl(args ...interface{}) (template.URL, error) {
if len(args) == 0 {
return "", fmt.Errorf("no arguments provided to reverse route")
}
action := args[0].(string)
if action == "Root" {
return template.URL(AppRoot), nil
}
actionSplit := strings.Split(action, ".")
if len(actionSplit) != 2 {
return "", fmt.Errorf("reversing '%s', expected 'Controller.Action'", action)
}
// Look up the types.
var c Controller
if err := c.SetAction(actionSplit[0], actionSplit[1]); err != nil {
return "", fmt.Errorf("reversing %s: %s", action, err)
}
// Unbind the arguments.
argsByName := make(map[string]string)
for i, argValue := range args[1:] {
Unbind(argsByName, c.MethodType.Args[i].Name, argValue)
}
return template.URL(MainRouter.Reverse(args[0].(string), argsByName).Url), nil
}
示例2: subjectGroupPage
func subjectGroupPage(e env.Env, w http.ResponseWriter, r *http.Request) {
if redir := checkRedirect(e, w, r, 2); redir {
return
}
header(e, w, r, 2)
defer footer(e, w, r)
path := strings.Split(r.URL.Path, "/")
subjID, err := strconv.Atoi(path[3])
if err != nil {
fmt.Fprintf(w, "Error: %v", err)
return
}
subj := e.Subjects[subjID]
f := getFilter(e, r)
g, err := e.GroupByFilteredClass(path[3], "", f)
if err != nil {
fmt.Fprintf(w, "Error: %v", err)
}
classes, err := e.Classes(path[3], f.Date)
if err != nil {
fmt.Fprintf(w, "Error: %v", err)
}
sort.Sort(sort.StringSlice(classes))
clsGrps := []subGroup{}
for _, c := range classes {
grp := g.SubGroup(group.Class(subj.Subj, c))
if len(grp.Students) > 0 {
clsGrps = append(clsGrps, subGroup{c, template.URL(c), grp})
}
}
data := struct {
Query template.URL
Year string
Subj *subject.Subject
SubGroups []subGroup
Matrix subGroupMatrix
Classes []subGroup
}{
template.URL(r.URL.RawQuery),
f.Year,
subj,
subGroups(g),
groupMatrix(g),
clsGrps,
}
err = e.Templates.ExecuteTemplate(w, "subjectgroups.tmpl", data)
if err != nil {
fmt.Fprintf(w, "Error: %v", err)
return
}
}
示例3: staticFileFn
func staticFileFn(p string) htemp.URL {
h, err := fileHashFn("static/" + p)
if err != nil {
log.Printf("WARNING could not read static file %s, %v", p, err)
return htemp.URL("/-/static/" + p)
}
return htemp.URL("/-/static/" + p + "?v=" + h)
}
示例4: Home
func (p githubPresenter) Home() *template.URL {
switch {
case strings.HasPrefix(p.repo.Root, "github.com/"):
url := template.URL("https://github.com/" + p.ghOwner + "/" + p.ghRepo)
return &url
default:
url := template.URL("http://" + p.repo.Root)
return &url
}
}
示例5: HomePage
func (this gitHubPresenter) HomePage() *template.URL {
switch goPackage := this.repo.GoPackages()[0]; {
case strings.HasPrefix(goPackage.Bpkg.ImportPath, "github.com/"):
url := template.URL("https://github.com/" + this.gitHubOwner + "/" + this.gitHubRepo)
return &url
default:
url := template.URL("http://" + goPackage.Bpkg.ImportPath)
return &url
}
}
示例6: AttendanceGroups
// AttendanceGroups produces a page with attendance summaries for the
// various student groups.
func AttendanceGroups(e env.Env) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if redir := checkRedirect(e, w, r, 0); redir {
return
}
header(e, w, r, 0)
defer footer(e, w, r)
f := getFilter(e, r)
g, err := e.GroupByFilter(f)
if err != nil {
fmt.Fprintf(w, "Error: %v", err)
return
}
type YearGroup struct {
Name string
Query template.URL
Groups []subGroup
Matrix subGroupMatrix
}
// Ignore error - will appear as blank string anyway
week, _ := e.CurrentWeek()
data := struct {
Week string
Query template.URL
YearGroups []YearGroup
}{
week,
template.URL(r.URL.RawQuery),
[]YearGroup{{"All Years", template.URL(""), subGroups(g), groupMatrix(g)}},
}
for year := 7; year < 15; year++ {
y := g.SubGroup(group.Year(year))
if len(y.Students) == 0 {
continue
}
yeargroup := YearGroup{fmt.Sprintf("Year %v", year),
template.URL(fmt.Sprintf("&year=%v", year)),
subGroups(y),
groupMatrix(y)}
data.YearGroups = append(data.YearGroups, yeargroup)
}
err = e.Templates.ExecuteTemplate(w, "attendancegroups.tmpl", data)
if err != nil {
fmt.Fprintf(w, "Error: %v", err)
}
}
}
示例7: submissionsAddHandler
func submissionsAddHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
if err := r.ParseForm(); err != nil {
serveErr(ctx, err, w)
return
}
ID, _, err := datastore.AllocateIDs(ctx, "Podcast", nil, 1)
if err != nil {
serveErr(ctx, err, w)
return
}
date, err := time.Parse(yyyymmdd, r.FormValue("date"))
if err != nil {
serveErr(ctx, err, w)
return
}
podcast := Podcast{
ID: ID,
Show: r.FormValue("show"),
Title: r.FormValue("title"),
Desc: r.FormValue("desc"),
URL: template.URL(r.FormValue("url")),
MediaURL: template.URL(r.FormValue("media_url")),
RuntimeSec: r.FormValue("runtime"),
Size: r.FormValue("size"),
Date: date,
Added: time.Now(),
}
if _, err := datastore.Put(ctx, datastore.NewKey(ctx, "Podcast", "", ID, nil), &podcast); err != nil {
serveErr(ctx, err, w)
return
}
key, err := datastore.DecodeKey(r.FormValue("key"))
if err != nil {
serveErr(ctx, err, w)
return
}
if err := datastore.Delete(ctx, key); err != nil {
serveErr(ctx, err, w)
return
}
if err := memcache.Delete(ctx, cacheKey); err != nil {
log.Errorf(ctx, "memcache delete error %v", err)
}
successTmpl.ExecuteTemplate(w, "base", nil)
}
示例8: UserEditPage
func UserEditPage(w http.ResponseWriter, req *http.Request) {
args := handlers.GetArgs(req)
username := args.Vars["username"]
page := editUserPage{
userPage: userPage{
User: args.User.Username,
Admin: handlers.Admin(args),
},
Permissions: []string{"read", "write", "admin"},
}
if username == "new-user" {
page.Links = []link{
{"quimby", "/"},
{"admin", "/admin.html"},
{"new user", "/admin/users/new-user"},
}
page.Actions = []action{
{Name: "cancel", URI: template.URL("/admin.html"), Method: "get"},
}
page.End = 0
} else {
u := quimby.NewUser(username, quimby.UserDB(args.DB))
if err := u.Fetch(); err != nil {
context.Set(req, "error", err)
return
}
q := url.Values{}
q.Add("resource", fmt.Sprintf("/admin/users/%s", username))
q.Add("name", username)
page.EditUser = u
page.Links = []link{
{"quimby", "/"},
{"admin", "/admin.html"},
{u.Username, fmt.Sprintf("/admin/users/%s", u.Username)},
}
page.Actions = []action{
{Name: "cancel", URI: template.URL("/admin.html"), Method: "get"},
{Name: "delete", URI: template.URL(fmt.Sprintf("/admin/confirmation?%s", q.Encode())), Method: "get"},
{Name: "update-password", URI: template.URL(fmt.Sprintf("/admin/users/%s/password", username)), Method: "get"},
{Name: "update-tfa", URI: template.URL(fmt.Sprintf("/admin/users/%s/tfa", username)), Method: "post"},
}
page.End = 3
}
if username == "new-user" {
templates["new-user.html"].template.ExecuteTemplate(w, "base", page)
} else {
templates["edit-user.html"].template.ExecuteTemplate(w, "base", page)
}
}
示例9: addTabletLinks
func (ex ZkExplorer) addTabletLinks(data string, result *ZkResult) {
t := &topo.Tablet{}
err := json.Unmarshal([]byte(data), t)
if err != nil {
return
}
if port, ok := t.Portmap["vt"]; ok {
result.Links["status"] = template.URL(fmt.Sprintf("http://%v:%v/debug/status", t.Hostname, port))
}
if !t.Parent.IsZero() {
result.Links["parent"] = template.URL(fmt.Sprintf("/zk/%v/vt/tablets/%v", t.Parent.Cell, t.Parent.TabletUidStr()))
}
}
示例10: initialize
func (s *Site) initialize() {
site := s
s.checkDirectories()
walker := func(path string, fi os.FileInfo, err error) error {
if err != nil {
PrintErr("Walker: ", err)
return nil
}
if fi.IsDir() {
site.Directories = append(site.Directories, path)
return nil
} else {
if ignoreDotFile(path) {
return nil
}
site.Files = append(site.Files, path)
return nil
}
}
filepath.Walk(s.absContentDir(), walker)
s.Info = SiteInfo{
BaseUrl: template.URL(s.Config.BaseUrl),
Title: s.Config.Title,
Recent: &s.Pages,
Config: &s.Config,
}
s.Shortcodes = make(map[string]ShortcodeFunc)
}
示例11: LargeGraph
func (g *GraphOptions) LargeGraph(gr GraphTarget, key string) template.URL {
params := url.Values{}
params.Set("height", "450")
params.Set("width", "800")
params.Set("bgcolor", "ff000000") // transparent
params.Set("fgcolor", "999999")
params.Set("yMin", "0")
params.Set("lineMode", "connected")
params.Set("drawNullAsZero", "false")
interval := fmt.Sprintf("%dsec", *statsdInterval/time.Second)
targets, color := gr.Target(key)
for _, target := range targets {
target = fmt.Sprintf(target, g.Prefix(gr.Host(), metricType(key)))
target = fmt.Sprintf(`summarize(%s,"%s","avg")`, target, interval)
if metricType(key) == "counter" {
scale := fmt.Sprintf("%.04f", 1/float64(*statsdInterval/time.Second))
target = fmt.Sprintf(`scale(%s,%s)`, target, scale)
}
log.Println("Adding target: ", target)
params.Add("target", target)
}
params.Add("colorList", color)
params.Set("from", g.GraphInterval.GraphFrom)
params.Set("until", g.GraphInterval.GraphUntil)
return template.URL(fmt.Sprintf("%s/render?%s", g.GraphiteUrl, params.Encode()))
}
示例12: Sparkline
func (g *GraphOptions) Sparkline(gr GraphTarget, key string) template.URL {
params := url.Values{}
params.Set("height", "20")
params.Set("width", "120")
params.Set("hideGrid", "true")
params.Set("hideLegend", "true")
params.Set("hideAxes", "true")
params.Set("bgcolor", "ff000000") // transparent
params.Set("fgcolor", "black")
params.Set("margin", "0")
params.Set("yMin", "0")
params.Set("lineMode", "connected")
params.Set("drawNullAsZero", "false")
interval := fmt.Sprintf("%dsec", *statsdInterval/time.Second)
targets, color := gr.Target(key)
for _, target := range targets {
target = fmt.Sprintf(target, g.Prefix(gr.Host(), metricType(key)))
params.Add("target", fmt.Sprintf(`summarize(%s,"%s","avg")`, target, interval))
}
params.Add("colorList", color)
params.Set("from", g.GraphInterval.GraphFrom)
params.Set("until", g.GraphInterval.GraphUntil)
return template.URL(fmt.Sprintf("%s/render?%s", g.GraphiteUrl, params.Encode()))
}
示例13: init
func init() {
// Filters is the default set of global filters.
revel.Filters = []revel.Filter{
revel.PanicFilter, // Recover from panics and display an error page instead.
revel.RouterFilter, // Use the routing table to select the right Action
revel.FilterConfiguringFilter, // A hook for adding or removing per-Action filters.
revel.ParamsFilter, // Parse parameters into Controller.Params.
revel.SessionFilter, // Restore and write the session cookie.
revel.FlashFilter, // Restore and write the flash cookie.
revel.ValidationFilter, // Restore kept validation errors and save new ones from cookie.
revel.I18nFilter, // Resolve the requested language
HeaderFilter, // Add some security based headers
revel.InterceptorFilter, // Run interceptors around the action.
revel.CompressFilter, // Compress the result.
revel.ActionInvoker, // Invoke the action.
}
// A template function we built because Polymer's iron-icon uses ":"
// in its icon attribute value. ":" will be parsed as escaped content
// by go's html/template.
//
// We choose template.URL because:
// 1. You can insert a link in the property, and
// 2. a ":" for defaults like "editor:publish" will work.
revel.TemplateFuncs["polymer_icon"] = func(attr string) template.URL {
return template.URL(attr)
}
// register startup functions with OnAppStart
// ( order dependent )
// revel.OnAppStart(InitDB)
// revel.OnAppStart(FillCache)
}
示例14: Image
func (this gitHubPresenter) Image() template.URL {
// Use the repo owner avatar image.
if user, _, err := gh.Users.Get(this.gitHubOwner); err == nil && user.AvatarURL != nil {
return template.URL(*user.AvatarURL)
}
return "https://github.com/images/gravatars/gravatar-user-420.png"
}
示例15: doTestShortcodeCrossrefs
func doTestShortcodeCrossrefs(t *testing.T, relative bool) {
var refShortcode string
var expectedBase string
if relative {
refShortcode = "relref"
expectedBase = "/bar"
} else {
refShortcode = "ref"
expectedBase = baseURL
}
path := filepath.FromSlash("blog/post.md")
in := fmt.Sprintf(`{{< %s "%s" >}}`, refShortcode, path)
expected := fmt.Sprintf(`%s/simple/url/`, expectedBase)
templ := tpl.New()
p, _ := pageFromString(simplePageWithURL, path)
p.Node.Site = &SiteInfo{
Pages: &(Pages{p}),
BaseURL: template.URL(helpers.SanitizeURLKeepTrailingSlash(baseURL)),
}
output, err := HandleShortcodes(in, p, templ)
if err != nil {
t.Fatal("Handle shortcode error", err)
}
if output != expected {
t.Errorf("Got\n%q\nExpected\n%q", output, expected)
}
}