简体   繁体   中英

json: cannot unmarshal object into Go value of type []*main.Config

I'm new to golang and json, we are using gorilla mux library and I'd like to do a post request in postman. In config struct entries needs to be a map like that and in post server I need to have an array of *Config in postServer struct. I have 3 go files. Service.go file is this:

package main

import (
"errors"
"github.com/gorilla/mux"
"mime"
"net/http"
)

type Config struct {
  Id      string            `json:"id"`
  entries map[string]string `json:"entries"`
}

type postServer struct {
  data map[string][]*Config
}

func (ts *postServer) createPostHandler(w http.ResponseWriter, req *http.Request) {
   contentType := req.Header.Get("Content-Type")
   mediatype, _, err := mime.ParseMediaType(contentType)
   if err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}

if mediatype != "application/json" {
    err := errors.New("Expect application/json Content-Type")
    http.Error(w, err.Error(), http.StatusUnsupportedMediaType)
    return
}

rt, err := decodeBody(req.Body)
if err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}

id := createId()
ts.data[id] = rt
renderJSON(w, rt)
}

func (ts *postServer) getAllHandler(w http.ResponseWriter, req *http.Request) {
allTasks := []*Config{}
for _, v := range ts.data {
    allTasks = append(allTasks, v...)
}

renderJSON(w, allTasks)
}
func (ts *postServer) getPostHandler(w http.ResponseWriter, req *http.Request) {
id := mux.Vars(req)["id"]
task, ok := ts.data[id]
if !ok {
    err := errors.New("key not found")
    http.Error(w, err.Error(), http.StatusNotFound)
    return
}
renderJSON(w, task)
}

func (ts *postServer) delPostHandler(w http.ResponseWriter, req *http.Request) {
id := mux.Vars(req)["id"]
if v, ok := ts.data[id]; ok {
    delete(ts.data, id)
    renderJSON(w, v)
} else {
    err := errors.New("key not found")
    http.Error(w, err.Error(), http.StatusNotFound)
}
}

I wanted to test createPostHandler. Then I have helper.go file where I decoded json into go and rendered into json:

package main

import (
"encoding/json"
"github.com/google/uuid"
"io"
"net/http"
)

func decodeBody(r io.Reader) ([]*Config, error) {
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()

var rt []*Config
if err := dec.Decode(&rt); err != nil {
    return nil, err
}
return rt, nil
}

func renderJSON(w http.ResponseWriter, v interface{}) {
js, err := json.Marshal(v)
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

w.Header().Set("Content-Type", "application/json")
w.Write(js)
}

func createId() string {
return uuid.New().String()
}

and the last one go file is main.go where I have this:

package main

import (
"context"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)

func main() {
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)

router := mux.NewRouter()
router.StrictSlash(true)

server := postServer{
    data: map[string][]*Config{},
}
router.HandleFunc("/config/", server.createPostHandler).Methods("POST")
router.HandleFunc("/configs/", server.getAllHandler).Methods("GET")
router.HandleFunc("/config/{id}/", server.getPostHandler).Methods("GET")
router.HandleFunc("/config/{id}/", server.delPostHandler).Methods("DELETE")

// start server
srv := &http.Server{Addr: "0.0.0.0:8000", Handler: router}
go func() {
    log.Println("server starting")
    if err := srv.ListenAndServe(); err != nil {
        if err != http.ErrServerClosed {
            log.Fatal(err)
        }
    }
}()

<-quit

log.Println("service shutting down ...")

// gracefully stop server
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

if err := srv.Shutdown(ctx); err != nil {
    log.Fatal(err)
}
log.Println("server stopped")

}

And JSON whad I did send is this:

{
"entries":["hello", "world"]
}

And error what I'm getting in postman is this:

json: cannot unmarshal object into Go value of type []*main.Config

I don't know what is a problem, maybe I'm sending wrong json or I just did something wrong in decodeBody, I needed to add [] in decodeBody in var rt []*Config because it wouldn't work otherwise. Can someone help me to fix this please?

This is an example of how you can define a struct Config that you can parse your sample JSON into.

EDIT: field entries changed to map.

You can play with it on Playground .

package main

import (
    "encoding/json"
    "fmt"
)

type Config struct {
    Id      string            `json:"id"`
    Entries map[string]string `json:"entries"`
}

func main() {
    str := `[{"id":"42", "entries":{"hello": "world"}}]`
    var tmp []Config
    err := json.Unmarshal([]byte(str), &tmp)
    if err != nil {
        fmt.Printf("error: %v", err)
    }
    var rt []*Config
    for _, c := range tmp {
        rt = append(rt, &c)
    }
    for _, c := range rt {
        for k, v := range c.Entries {
            fmt.Printf("id=%s key=%s value=%s\n", c.Id, k, v)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM