如何将变量及其值发送到html

I have written a small piece of code in go

func loginHandler(w http.ResponseWriter, r *http.Request) {
    log.Println("loginHandler")
    log.Println("request url is", r.RequestURI)
    log.Println("request method", r.Method)
    requestbody, _ := ioutil.ReadAll(r.Body)
    log.Println("request body is", string(requestbody))
    if r.Method == "POST" {
        us, err := globalSessions.SessionStart(w, r)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        us.Set("LoggedInUserID", "000000")
        w.Header().Set("Location", "/auth")
        w.WriteHeader(http.StatusFound)
        return
    }
    outputHTML(w, r, "static/login.html")
}

func outputHTML(w http.ResponseWriter, req *http.Request, filename string) {
    log.Println("outputHTML")
    requestbody, _ := ioutil.ReadAll(req.Body)
    log.Println("request body is", string(requestbody))
    log.Println("request body is", requestbody)
    file, err := os.Open(filename)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
    defer file.Close()
    fi, _ := file.Stat()
    http.ServeContent(w, req, file.Name(), fi.ModTime(), file)
}

in this code i am redirecting to login.html . now i want to send a variable let it be some string called testvariable and its value to login.html.

</div>

To be able to display values in your html you can use Go's html/template package.

First you'll need to specify where in the html page you want your values to appear, using the html/template package you can do that with template actions.

"Actions"--data evaluations or control structures--are delimited by "{{" and "}}"

Next you'll need to drop the http.ServeContent function as that does not know how to render templates, instead you can use Execute to display the login page together with your values.

Here's an example:

login.html:

<html>
    <body>
        <h1>{{.MyVar}}</h1>
    </body>
</html>

outputHTML:

func outputHTML(w http.ResponseWriter, filename string, data interface{}) {
    t, err := template.ParseFiles(filename)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
    if err := t.Execute(w, data); err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
}

And your loginHandler:

func loginHandler(w http.ResponseWriter, r *http.Request) {

    // do whatever you need to do

    myvar := map[string]interface{}{"MyVar": "Foo Bar Baz"}
    outputHTML(w, "static/login.html", myvar)
}

Read more on templates here: html/template and for information about how to program the templates themselves, see the documentation for text/template