Sorry im beginner and i read golang.docs but didnt understand well.
i`ve : index.html:
<html>
<head>
</head>
<body>
<form action type="checkbox" name="test" value="A" {{.checked}}>
<input type="submit" value="save">
</body>
</html>
in main.go
if user click save button then check checkbox redirect that page and show checkbox checked
You could send variables in map. For example:
package main
import (
"bytes"
"fmt"
"text/template"
)
func main() {
t, _ := template.New("hi").Parse("Hi {{.name}}")
var doc bytes.Buffer
t.Execute(&doc, map[string]string{"name": "Peter"})
fmt.Println(doc.String()) //Hi Peter
}
The . is defined in go code.
Please provide the snippet of your go code where the template is executed, something like the following codes:
t, _ := template.ParseFiles(tmpl + ".html")
t.Execute(w, data) // the data must feature the field "checked"
Or
templates.ExecuteTemplate(w, tmpl+".html", data) // the data must feature the field "checked"
You can pass any type(interface{}) to a functions that execute a template as "data". Usually it is a Struct or a Map[string]string.
How to set the checked
Probably the "checked" is setted in the main.go at handler according to the posted form.
Read the docs and explain it better. Please
Related
I'm using gorilla serve mux to serve static html files.
r := mux.NewRouter()
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public"))).Methods("GET")
I do have a Index.html file inside the public folder as well as other html files.
When browsing the site I get all the content of the folder instead of the default Index.html.
I came from C# and I know that IIS takes Index.html as default but it is possible to select any page as a default.
I wanted to know if there's a proper way to select a default page to serve in Gorilla mux without creating a custom handler/wrapper.
Maybe using a custom http.HandlerFunc would be easier:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Here you can check if path is empty, you can render index.html
http.ServeFile(w, r, r.URL.Path)
})
You do have to make a custom handler because you want a custom behavior. Here, I just wrapped the http.FileServer handler.
Try this one:
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
handler := mux.NewRouter()
fs := http.FileServer(http.Dir("./public"))
handler.PathPrefix("/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
//your default page
r.URL.Path = "/my_default_page.html"
}
fs.ServeHTTP(w, r)
})).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", handler))
}
So, from the code, if the visited path is the root (/) then you rewrite the r.URL.Path to your default page, in this case my_default_page.html.
After grabthefish mentioned it i decided to check the actual code of gorilla serve mux.
This code is taken from net/http package which Gorilla mux is based on.
func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string,
redirect bool) {
const indexPage = "/index.html"
// redirect .../index.html to .../
// can't use Redirect() because that would make the path absolute,
// which would be a problem running under StripPrefix
if strings.HasSuffix(r.URL.Path, indexPage) {
localRedirect(w, r, "./")
return
}
the code request the index file to be index.html in lower case so renaming my index file solved it.
thank you grabthefish!
I am trying to figure out what method is called when I show a variable in an "html/template" template in Go via {{ .SomeVariable }}.
I am using the package "html/template".
I am using this function to render a template:
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
t, _ := template.ParseFiles("public/" + tmpl + ".html")
t.Execute(w, p)
}
with
type Page struct {
Title string
Users []*model.User
}
and an example template
<html>
<head>
<title>Listing Users</title>
</head>
<body>
<h1>Listing users</h1>
{{range .Params}}
<h3>
id {{.Id }}
email {{.Email}}
name {{.Name}}
</h3>
{{end}}
</body>
</html>
We store Id in a certain way and have a .String() method defined for displaying it.
When we use the package "text/template" the Id attribute displays correctly but when we use "html/template" it does not. My guess is that the former is calling .String() when displaying a variable and latter is not. I haven't been able to glean from the documentation what method is being called.
This is the first SO question I've ever written for Go. Hopefully made it clear but feel free to ask for additional info as I am a complete Go noob.
Thanks.
I'm writing a web server in Go and was asking myself, what the conventional way of conditionally hiding a part of an HTML page is.
If I wanted a "sign in" button only to show up, when the user is NOT logged in, how would I achieve something like this?
Is it achieved with template engines or something else?
Thank you for taking the time to read and answer this :)
you just have to give a struct to your template and manage the rendering inside it.
Here is a working exemple to test:
package main
import (
"html/template"
"net/http"
)
func main() {
http.HandleFunc("/", helloHandler)
http.ListenAndServe(":8000", nil)
}
type User struct {
Name string
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
t := template.New("logged exemple")
t, _ = t.Parse(`
<html>
<head>
<title>Login test</title>
</head>
<body>
{{if .Logged}}
It's me {{ .User.Name }}
{{else}}
-- menu --
{{end}}
</body>
</html>
`)
// Put the login logic in a middleware
p := struct {
Logged bool
User *User
}{
Logged: true,
User: &User{Name: "Mario"},
}
t.Execute(w, p)
}
To manage the connexion you can use http://www.gorillatoolkit.org/pkg/sessions with https://github.com/codegangsta/negroni and create the connection logic inside a middleware.
Simply start session on user login .Set the necessary values in session and then hide the html u want with if tag in javascript using session. Its very simple and best way to solve this type of problems.
You might try something like this
<?php
if($_SESSION['user']){}else{
echo '<button onclick="yourfunction();">sign in</button>';
}
?>
Thus, if they aren't logged in, this'll show up.
I have a html page that has the follow code.
<form action="/image" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
I then have some Go code to get the file on the back end.
func uploaderHandler(w http.ResponseWriter, r *http.Request) {
userInput := r.FormValue("file")
but anytime I try to use userInput from the go script, it returns nothing. Am I passing the variables wrong?
EDIT: I know how to upload things to golang that are text/passwords. I am having trouble uploading images to Go with the code.
EDIT 2: Read the Go guide a found the solution. See below.
First you need to use req.FormFile not FormValue, then you will have to manually save the image to a file.
Something like this:
func HandleUpload(w http.ResponseWriter, req *http.Request) {
in, header, err := req.FormFile("file")
if err != nil {
//handle error
}
defer in.Close()
//you probably want to make sure header.Filename is unique and
// use filepath.Join to put it somewhere else.
out, err := os.OpenFile(header.Filename, os.O_WRONLY, 0644)
if err != nil {
//handle error
}
defer out.Close()
io.Copy(out, in)
//do other stuff
}
I've got this simple go lang webserver that does nothing more but parsing some data into an external HTML file and serve that file to the webserver.
package main
import (
"html/template"
"net/http"
)
type Event struct {
Name string
}
func handler(w http.ResponseWriter, r *http.Request) {
e := Event{ Name: "Melt! Festival" }
t, _ := template.ParseFiles("events.html")
t.Execute(w, e)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":1337", nil)
}
But whenever I try to parse the HTML file with the set it parses my html-page as text in stead of rendering the HTML in the browser
<!DOCTYPE>
<html>
<head>
<title>Event</title>
</head>
<body>
<p>
Event: {{.Name}}
</p>
</body>
</html>
When I leave the <!DOCTYPE> out of the HTML-file it renders it just fine.
Can anyone tell me why this is because I'm really curious? I spent two hours searching for the cause of my go code not working.
Your doctype declaration is incorrect, thus having an effect opposite from the desired one : it is probably interpreted by the browser as signifying the document isn't HTML.
Use this :
<!DOCTYPE html>
See reference.
Have you tried using DOCTYPE html in your file instead?