GO:作为Fprintf参数传递的不正确的表单值类型

I'm trying to print a user's username that the user keyed into a form, using Fprintf:

GO code:

const logPage = `
<html>
<form action="/login" method="POST">
    <label for="name">Username</label>
        <input type="text" id="Username" name="name"></input>
    ...
</form> 
</html>
`
const homePage = `
<html>
<h1>hi %s</h1>
</html>
`

func homehandler(w http.ResponseWriter, r *http.Request) {
    a = r.FormValue("name")
    fmt.Fprintf(w, homePage, a) ---> how do I insert the a value in the required interface{} form?
}

func main() {
    http.HandleFunc("/home", homehandler)
    ...
}

According to this: http://golang.org/pkg/net/http/#Request.FormValue, FormValue returns a string, but Fprintf seems to require an interface type: http://golang.org/pkg/fmt/#Fprintf. How do I insert the correct value/type of "a" as in my code above? Or, is there a better way to do this?

I am actually not sure if your code could work the way you intend it.

Here's a slightly modifiede, working example:

const logPage = `
<html>
<form action="/login" method="POST">
    <label for="name">Username</label>
        <input type="text" id="Username" name="name"></input>
    ...
</form> 
</html>
`
const homePage = `
<html>
<h1>hi %s</h1>
</html>
`


func loginhandler(w http.ResponseWriter, r *http.Request) {
  if r.Method == "GET" {
    fmt.Fprint(w, homePage)
  } else if r.Method == "POST" {
    // Here you can check the credentials
    // or print the page you wanted to
    // BUT please DON'T DO THIS
    a = r.FormValue("name")        
    fmt.Fprint(w, logpage, a)
    // DON'T DO THIS FOR THE SAKE OF YOUR USERS
  }
}

func main() {
    // http.HandleFunc("/home", homehandler) not needed
    http.HandleFunc("/login", loginhandler)
    ...
}

Here is how it goes:

  1. The user makes a GET request to your /login page, and the loginHandler is called.
  2. In your loginhandler you are returning the login page html to the user's browser.
  3. Then the user enters it's data, and sends a POST request.
  4. In the loginhandler the differentiation between the types of requests make it possible to either render the form, or display the values posted.

However, you should ALWAYS sanitize user data. The template/html does that for you, so please take a look. If you have other questions concerning the usage of that package, aks away!