lundi 23 mars 2020

How to handle json in Golang's static web server?

I have a simple static web server based on 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? I am new to Go




Aucun commentaire:

Enregistrer un commentaire