You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the provided sample code, after a successful HTTP request, result["data"] changes type from getIP to map[string]interface{}. I don't know if this is feature or a bug, but it is unexpected and annoying to use. This does not happen if the outer map is replaced with a struct.
package main
import (
"encoding/json"
"log"
"net/http"
"net/netip"
"github.com/davecgh/go-spew/spew"
"github.com/go-resty/resty/v2"
)
type getIP struct {
Address string `json:"address"`
Version int `json:"version"`
}
const serveAddr = ":48916"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
addr := netip.MustParseAddrPort(r.RemoteAddr).Addr().String()
result := map[string]any{
"data": getIP{
Address: addr,
Version: 4,
},
}
enc := json.NewEncoder(w)
if err := enc.Encode(result); err != nil {
log.Fatalln(err)
}
})
go func() {
if err := http.ListenAndServe(serveAddr, nil); err != http.ErrServerClosed {
log.Fatalf("Error starting server: %v\n", err)
}
}()
result := map[string]any{
"data": getIP{},
}
spew.Dump(result)
r := resty.New().R().SetResult(&result)
httpResp, err := r.Get("http://localhost" + serveAddr)
if err != nil {
log.Fatalf("unable to contact service: %v\n", err)
}
if httpResp.IsError() {
log.Fatalf("error contacting service: %s\n", httpResp.Status())
}
spew.Dump(result)
}
The text was updated successfully, but these errors were encountered:
@maticmeznar Thanks for reaching out.
I don't know if this expected result could be achieved the way it is. You could try to define a custom type for the outer map.
@kecci Thanks for responding to the comment. Could you explain what to consider? I'm unable to understand.
In the provided sample code, after a successful HTTP request, result["data"] changes type from getIP to map[string]interface{}. I don't know if this is feature or a bug, but it is unexpected and annoying to use. This does not happen if the outer map is replaced with a struct.
The text was updated successfully, but these errors were encountered: