import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) func main() { // create a new empty scheme scheme := runtime.NewScheme() // add the necessary types to the scheme metav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion) // create an object to encode obj := &metav1.ObjectMeta{ Name: "example", Namespace: "default", } // encode the object to JSON using the scheme encoder := runtime.EncodeJSON(scheme) json, err := encoder.Encode(obj) if err != nil { ... } // print the JSON string to the console fmt.Println(string(json)) }
import ( "net/http" "io/ioutil" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) func someHandler(w http.ResponseWriter, r *http.Request) { // read the request body body, err := ioutil.ReadAll(r.Body) if err != nil { ... } // create a new decoder instance with our scheme scheme := runtime.NewScheme() metav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion) decoder := scheme.NewDecoder() // use the decoder to decode the request body obj := &metav1.ObjectMeta{} err = decoder.Decode(body, nil, obj) if err != nil { ... } // perform some operations on the object obj.Name = "newname" // encode the object back into JSON using the scheme encoder := runtime.EncodeJSON(scheme) json, err := encoder.Encode(obj) if err != nil { ... } // set the response header and body w.Header().Set("Content-Type", "application/json") w.Write(json) }