Как обрабатывать JSON на веб-сервере stati c? - PullRequest
0 голосов
/ 24 марта 2020

У меня есть простой веб-сервер stati c, написанный на 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)
}

Он обслуживает все файлы stati c, такие как css, js, html и json. Однако, только для файла JSON, я хочу, чтобы Go вошел в среду выполнения, проанализировал его и отобразил специально разработанный код HTML. Текущая функция-обработчик является расширением http.FileServer. Могу ли я указать здесь свой логин?

1 Ответ

0 голосов
/ 24 марта 2020

Если я вас понимаю, вы хотите включить JSON внутри веб-страницы HTML, правильно? Если это так, посмотрите на пакет go "html / template" .

Вы можете изменить файл html на шаблон.

{{define "jsonInHTML"}}

{{ .InsertJSON }}

{{end}}

Затем в вашем Go обработчике сервера

fun c 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)

}

...