Go – building POST body, receive error "invalid composite literal type string"

Issue

I’m trying to build a POST body in Go, but I keep getting the following error:

invalid composite literal type string

Snippets of my code and structs are below, I’m can’t figure out what I’m doing wrong?

postData := projectPostData{
    Filters: projectFilters{
        Name: string{ // <-- Error is referred to on this line 
            target,
        },
    },
}

type projectPostData struct {
    Filters projectFilters `json:"filters,omitempty"`
}

type projectFilters struct {
    Name string `json:"name,omitempty"`
}

Solution

You can check the below code:

package main 

import(
    "fmt"
)


type projectFilters struct {
    Name string `json:"string,omitempty"`
}

type projectPostData struct {
    Filters projectFilters `json:"filters,omitempty"`
}



func main(){
    target := "test target"

    postData := projectPostData{
        Filters: projectFilters{
            Name: target,
        },
    }
    
    fmt.Println(postData)
}

Answered By – code0x00

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.