Ankur
Ankur

Reputation: 127

How to handle JSON in static web server?

I have a simple static web server written in Go:

package main

import (
        "net/http"
        "log"
        "flag"
)

type myfs struct {
    http.Dir
}

func (m myfs) Open(name string) (result http.File, err error) {
    f, err := m.Dir.Open(name)
    if err != nil {
        return
    }

    fi, err := f.Stat()
    if err != nil {
        return
    }
    if fi.IsDir() {
        // Return a response that would have been if directory would not exist:
        return m.Dir.Open("does-not-exist")
    }
    return f, nil
}

func main() {
    directory := flag.String("d", "./static", "the directory of static file to host")
    handler := http.FileServer(myfs{http.Dir(*directory)})
//        http.Handle("/", http.FileServer(http.Dir("./static")))
        http.Handle("/", handler)
        err := http.ListenAndServe(":8000", nil)
    log.Fatal(err)
}

It is serving all static files pretty well such as css, js, html and json. However just for JSON file, I want Go to come into the runtime, parse it and render a custom developed HTML code. The current handler function is an extension of http.FileServer, can I put my login in that?

Upvotes: 0

Views: 732

Answers (1)

John Scharber
John Scharber

Reputation: 73

If I understand you, what you want is to include the JSON inside of the HTML web page, correct? If so, look at the go "html/template" package.

You can modify your html file to be a template.

{{define "jsonInHTML"}}

{{ .InsertJSON }}

{{end}}

Then in your Go server handler

func rootHandler(wr http.ResponseWriter, req *http.Request) {

tmpl, err := template.New("name").Parse(...)

// Get the JSON form the body
InsertJSN, err := ioutil.ReadAll(req.Body)

// Execute the template passing the http.ResponseWriter, and the  
err := template.ExecuteTemplate(wr, "name", InsertJSON)

}

Upvotes: 1

Related Questions