Невозможно написать универсальную функцию, которая может работать с несколькими структурами в Golang.
Я новичок в Go и изучаю интерфейсы и структуры. Я имею 2 - Структуры ServiceSection и SliderSection , и я пытаюсь выполнить следующие 2 задачу с каждым из самих по
- ПОЛУЧИТЕ ответ JSON и демаршалируйте его.
- Используйте структуру для создания HTML с помощью "html / template"
Поэтому я пытаюсь создать общую функцию для выполнения обеих задач, которые могут работать для нескольких структур. Планируется создать еще 5-6 таких структур. Ниже приведен созданный мной код.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"html/template"
)
const (
getServicesAPI = "https://huyk1a44n6.execute-api.us-east-1.amazonaws.com/v1/services"
getSliderAPI = "https://huyk1a44n6.execute-api.us-east-1.amazonaws.com/v1/home-slider"
servicesTemplate = `<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section-title">
<h5>{{.Heading1}}</h5>
<h2>{{.Heading2}}</h2>
</div>
</div>
</div>
<div class="row">
{{range .Services}}
<div class="col-lg-4 col-md-6">
<a class="single-services-box" href="{{.Href}}">
<div class="services-img">
<img alt="Service Images"
src="{{.Image}}">
</div>
<h3>{{.Heading}}</h3>
</a>
</div>
{{end}}
</div>
</div>`
sliderTemplate = ` {{range .Slider}}
<div class="home-slider flickity-dots-absolute" data-flickity='{ "bgLazyLoad": 1, "bgLazyLoad": true, "fade": true, "prevNextButtons": false, "autoPlay": 7000, "pauseAutoPlayOnHover": false }'>
<div class="home-slider-single-item" data-flickity-bg-lazyload="{{.Image}}">
<div class="container">
<div class="row d-flex align-items-center">
<div class="col">
<div class="home-slider-content">
<h1 class="home-slider-title">{{.title}}</h1>
<div class="home-slider-description">
<p>{{.description}}</p>
</div>
<div class="home-slider-btn-box">
<a class="button home-btn-1 mr-15" href="{{.button1_href}}">{{.button1_title}}</a>
<a class="button btn-primary" href="{{.button2_href}}">{{.button1_title}}</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{{end}}
`
)
type ServiceSection struct {
Heading1 string `json:"Heading1"`
Heading2 string `json:"Heading2"`
Services []struct {
Image string `json:"Image"`
Href string `json:"Href"`
Heading string `json:"Heading"`
} `json:"Services"`
}
type SliderStruct struct {
Title string `json:"title"`
Description string `json:"description"`
Button1Title string `json:"button1_title"`
Button1Href string `json:"button1_href"`
Button2Title string `json:"button2_title"`
Button2Href string `json:"button2_href"`
Image string `json:"Image"`
}
type SliderSection struct {
Slider []SliderStruct
}
type MyInterface interface {
populateHTML(string, string)
}
func (ss ServiceSection) populateHTML(endpoint string, tmpl string) {
populateHTMLcommon(ss, endpoint, tmpl)
}
func (ss SliderSection) populateHTML(endpoint string, tmpl string) {
populateHTMLcommon(ss, endpoint, tmpl)
}
func main() {
println("WASM Go Initialized")
ServiceSec := ServiceSection{}
SliderSec := SliderSection{}
ServiceSec.populateHTML(getServicesAPI, servicesTemplate)
SliderSec.populateHTML(getSliderAPI, sliderTemplate)
}
func populateHTMLcommon(hs MyInterface, endpoint string, tmplStr string) {
fmt.Println("struct ServiceSection", hs, endpoint)
// GET API CALL
fmt.Println("Inside getDataFromAPI()")
response, err := http.Get(endpoint)
if err != nil {
log.Fatal(err)
}
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(responseData, &hs)
if err != nil {
log.Fatal(err)
}
// Create HTML using template
tmpl := template.Must(template.New("table").Parse(tmplStr))
buf := new(bytes.Buffer) // Buffer created to hold the final HTML
err = tmpl.Execute(buf, responseData) // Populate the data in the HTML template
if err != nil {
log.Fatal(err)
}
tableHTMLString := buf.String()
fmt.Println("tableHTMLString: ", tableHTMLString)
}
При выполнении вышеуказанной программы я получаю следующую ошибку в функции populateHTMLcommon () при демаршалинге JSON -
json: невозможно демаршалировать объект в значение Go типа main.MyInterface
Это означает, что он не может идентифицировать соответствующую структуру из интерфейса MyInterface .
Я не понимаю, как я могу создать общую функцию, которая могла бы работать с несколькими структурами. Любая помощь приветствуется.
1 ответ
A couple of things:
- A Go interface is an abstraction - so it's rare, if ever, that you need to get the address of an interface
- if a struct's method needs to change the state of the struct (and persist the change), use a pointer receiver.
So to fix your immediate problems:
// err = json.Unmarshal(responseData, &hs) // address of an interface usually is not what you want
err = json.Unmarshal(responseData, hs)
and update your method signatures to use pointer-receivers:
func (ss *ServiceSection) populateHTML(endpoint string, tmpl string) {
populateHTMLcommon(ss, endpoint, tmpl)
}
func (ss *SliderSection) populateHTML(endpoint string, tmpl string) {
populateHTMLcommon(ss, endpoint, tmpl)
}