Best Got code snippet using gop.JSONStr
application_controller.go
Source:application_controller.go
1/*2Copyright 2022.3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package appstudioredhatcom14import (15 "context"16 "encoding/json"17 "fmt"18 "reflect"19 "strings"20 "k8s.io/apimachinery/pkg/runtime"21 ctrl "sigs.k8s.io/controller-runtime"22 "sigs.k8s.io/controller-runtime/pkg/client"23 "sigs.k8s.io/controller-runtime/pkg/log"24 sharedutil "github.com/redhat-appstudio/managed-gitops/backend-shared/util"25 "crypto/sha256"26 apierrors "k8s.io/apimachinery/pkg/api/errors"27 attributes "github.com/devfile/api/v2/pkg/attributes"28 "github.com/go-logr/logr"29 applicationv1alpha1 "github.com/redhat-appstudio/application-service/api/v1alpha1"30 devfile "github.com/redhat-appstudio/application-service/pkg/devfile"31 gitopsdeploymentv1alpha1 "github.com/redhat-appstudio/managed-gitops/backend/apis/managed-gitops/v1alpha1"32 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"33)34// ApplicationReconciler reconciles a Application object35type ApplicationReconciler struct {36 client.Client37 Scheme *runtime.Scheme38}39const deploymentSuffix = "-deployment"40//+kubebuilder:rbac:groups=appstudio.redhat.com,resources=applications,verbs=get;list;watch;create;update;patch;delete41//+kubebuilder:rbac:groups=appstudio.redhat.com,resources=applications/status,verbs=get;update;patch42//+kubebuilder:rbac:groups=appstudio.redhat.com,resources=applications/finalizers,verbs=update43//+kubebuilder:rbac:groups=managed-gitops.redhat.com,resources=gitopsdeployments,verbs=get;list;watch;create;update;patch;delete44//+kubebuilder:rbac:groups=managed-gitops.redhat.com,resources=gitopsdeployments/status,verbs=get;update;patch45//+kubebuilder:rbac:groups=managed-gitops.redhat.com,resources=gitopsdeployments/finalizers,verbs=update46// Reconcile is part of the main kubernetes reconciliation loop which aims to47// move the current state of the cluster closer to the desired state.48func (r *ApplicationReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {49 log := log.FromContext(ctx)50 log.Info("Detected AppStudio Application event:", "request", req)51 var asApplication applicationv1alpha1.Application52 if err := r.Client.Get(ctx, req.NamespacedName, &asApplication); err != nil {53 if apierrors.IsNotFound(err) {54 // A) Application has been deleted, so ensure that GitOps deployment is deleted.55 err := processDeleteGitOpsDeployment(ctx, req, r.Client, log)56 return ctrl.Result{}, err57 } else {58 log.Error(err, "unexpected error on retrieving AppStudio Application", "req", req)59 return ctrl.Result{}, err60 }61 }62 // Convert the app name to corresponding GitOpsDeployment name, ensuring that the GitOpsDeployment name fits within 64 chars63 gitopsDeplName := sanitizeAppNameWithSuffix(asApplication.Name, deploymentSuffix)64 gitopsDeployment := &gitopsdeploymentv1alpha1.GitOpsDeployment{65 ObjectMeta: metav1.ObjectMeta{66 Name: gitopsDeplName,67 Namespace: asApplication.Namespace,68 },69 }70 if err := r.Client.Get(ctx, client.ObjectKeyFromObject(gitopsDeployment), gitopsDeployment); err != nil {71 if apierrors.IsNotFound(err) {72 // B) GitOpsDeployment doesn't exist, but Application does, so create the GitOpsDeployment73 // Sanity check the application before we do anything more with it74 if err := validateApplication(asApplication); err != nil {75 return ctrl.Result{}, err76 }77 err := processCreateGitOpsDeployment(ctx, asApplication, r.Client, log)78 return ctrl.Result{}, err79 } else {80 log.Error(err, "unexpected error on retrieving GitOpsDeployment", "req", req)81 return ctrl.Result{}, err82 }83 }84 // C) GitOpsDeployment exists, and Application exists, so check if they differ. If so, update the old one.85 // Sanity check the application before we do anything more with it86 if err := validateApplication(asApplication); err != nil {87 return ctrl.Result{}, err88 }89 gopFromApplication, err := generateNewGitOpsDeploymentFromApplication(asApplication)90 if err != nil {91 return ctrl.Result{}, fmt.Errorf("unable to convert Application to GitOpsDeployment: %v", err)92 }93 if reflect.DeepEqual(gopFromApplication.Spec, gitopsDeployment.Spec) {94 // D) Both exist, but there is no different, so no-op.95 log.V(sharedutil.LogLevel_Debug).Info(fmt.Sprintf("GitOpsDeployment '%s' is unchanged from Application, so did not require an update.",96 gitopsDeployment.Namespace+"/"+gitopsDeployment.Name))97 return ctrl.Result{}, nil98 }99 // Replace the old spec field with the new spec field100 gitopsDeployment.Spec = gopFromApplication.Spec101 if log.V(sharedutil.LogLevel_Debug).Enabled() {102 jsonStr, err := json.Marshal(gitopsDeployment.Spec)103 if err != nil {104 return ctrl.Result{}, err105 }106 log.V(sharedutil.LogLevel_Debug).107 Info(fmt.Sprintf("updating GitOpsDeployment '%s' with new spec: '%s'",108 gitopsDeployment.Namespace+"/"+gitopsDeployment.Name, string(jsonStr)))109 } else {110 log.Info(fmt.Sprintf("updating GitOpsDeployment '%s' with new spec",111 gitopsDeployment.Namespace+"/"+gitopsDeployment.Name))112 }113 if err := r.Client.Update(ctx, gitopsDeployment); err != nil {114 return ctrl.Result{}, err115 }116 return ctrl.Result{}, nil117}118// processDeleteGitOpsDeployment deletes the GitOpsDeployment that corresponds to req119func processDeleteGitOpsDeployment(ctx context.Context, req ctrl.Request, k8sClient client.Client, log logr.Logger) error {120 gitopsDeplName := sanitizeAppNameWithSuffix(req.Name, deploymentSuffix)121 gitopsDepl := &gitopsdeploymentv1alpha1.GitOpsDeployment{122 ObjectMeta: metav1.ObjectMeta{123 Name: gitopsDeplName,124 Namespace: req.Namespace,125 },126 }127 if err := k8sClient.Get(ctx, client.ObjectKeyFromObject(gitopsDepl), gitopsDepl); err != nil {128 if apierrors.IsNotFound(err) {129 // Application doesn't exist, and GitOpsDeployment also doesn't exist, so no work to do.130 return nil131 } else {132 return fmt.Errorf("unable to retrieve gitopsdepl '%s': %v", gitopsDeplName, err)133 }134 }135 if err := k8sClient.Delete(ctx, gitopsDepl); err != nil {136 return fmt.Errorf("unable to delete gitopsdepl '%s': %v", gitopsDeplName, err)137 }138 return nil139}140// processCreateGitOpsDeployment creates the GitOpsDeployment that corresponds to 'asApplication'141func processCreateGitOpsDeployment(ctx context.Context, asApplication applicationv1alpha1.Application, client client.Client, log logr.Logger) error {142 // Since the GitOpsDeployment doesn't exist, we create it.143 // Sanity check the application144 if err := validateApplication(asApplication); err != nil {145 return err146 }147 gitopsDepl, err := generateNewGitOpsDeploymentFromApplication(asApplication)148 if err != nil {149 return fmt.Errorf("unable to convert Application to GitOpsDeployment: %v", err)150 }151 log.Info("creating new GitOpsDeployment '" + gitopsDepl.Name + "' (" + string(gitopsDepl.UID) + ")")152 if err := client.Create(ctx, &gitopsDepl); err != nil {153 return fmt.Errorf("unable to create GitOpsDeployment '%s': %v", gitopsDepl.Name, err)154 }155 return nil156}157// Sanity test the application158func validateApplication(asApplication applicationv1alpha1.Application) error {159 if strings.TrimSpace(asApplication.Name) == "" {160 return fmt.Errorf("application resource has invalid name: '%s'", asApplication.Name)161 }162 if strings.TrimSpace(asApplication.Status.Devfile) == "" {163 return fmt.Errorf("application status' devfile field is empty")164 }165 _, _, _, err := getGitOpsRepoData(asApplication)166 if err != nil {167 return fmt.Errorf("unable to validate application: %v", err)168 }169 return nil170}171func getGitOpsRepoData(asApplication applicationv1alpha1.Application) (string, string, string, error) {172 var err error173 curDevfile, err := devfile.ParseDevfileModel(asApplication.Status.Devfile)174 if err != nil {175 return "", "", "", fmt.Errorf("unable to parse devfile model: %v", err)176 }177 // Need to reset the err to nil after it is used, because GetString() doesn't clear old errors.178 err = nil179 // These strings are not defined as constants in the application service repo180 metadata := curDevfile.GetMetadata()181 // GitOps Repository is a required field182 gitopsURL := metadata.Attributes.GetString("gitOpsRepository.url", &err)183 if err != nil {184 return "", "", "", fmt.Errorf("unable to retrieve gitops url: %v", err)185 }186 if strings.TrimSpace(gitopsURL) == "" {187 return "", "", "", fmt.Errorf("gitops url is empty")188 }189 err = nil190 // Branch is not a required field191 branch := metadata.Attributes.GetString("gitOpsRepository.branch", &err)192 if err != nil {193 // Ignore KeyNotFoundErrors, but otherwise report the error and return194 if _, ok := (err).(*attributes.KeyNotFoundError); !ok {195 return "", "", "", fmt.Errorf("unable to retrieve gitops repo branch: %v", err)196 }197 }198 err = nil199 // Context is a required field200 context := metadata.Attributes.GetString("gitOpsRepository.context", &err)201 if err != nil {202 return "", "", "", fmt.Errorf("unable to retrieve gitops repo context: %v", err)203 }204 if strings.TrimSpace(context) == "" {205 return "", "", "", fmt.Errorf("gitops repo context is empty: %v", err)206 }207 // Argo CD expects a "non-absolute" path here. Argo CD interprets "/" as absolute, so change it to "."208 // to indicate the root.209 if context == "/" {210 context = "."211 }212 return gitopsURL, branch, context, nil213}214// generateNewGitOpsDeploymentFromApplication converts the Application into a corresponding GitOpsDeployment, by215// matching their corresponding fields.216func generateNewGitOpsDeploymentFromApplication(asApplication applicationv1alpha1.Application) (gitopsdeploymentv1alpha1.GitOpsDeployment, error) {217 url, branch, context, err := getGitOpsRepoData(asApplication)218 if err != nil {219 return gitopsdeploymentv1alpha1.GitOpsDeployment{}, err220 }221 gitopsDeplName := sanitizeAppNameWithSuffix(asApplication.Name, "-deployment")222 res := gitopsdeploymentv1alpha1.GitOpsDeployment{223 ObjectMeta: metav1.ObjectMeta{224 Name: gitopsDeplName,225 Namespace: asApplication.Namespace,226 Labels: map[string]string{227 // Add a label which contains a reference to the actual name of the parent Application resource228 "appstudio.application.name": asApplication.Name,229 },230 // When the parent is deleted, the child should be deleted too231 OwnerReferences: []metav1.OwnerReference{{232 APIVersion: asApplication.APIVersion,233 Kind: asApplication.Kind,234 Name: asApplication.Name,235 UID: asApplication.UID,236 }},237 },238 Spec: gitopsdeploymentv1alpha1.GitOpsDeploymentSpec{239 Source: gitopsdeploymentv1alpha1.ApplicationSource{240 RepoURL: url,241 Path: context,242 TargetRevision: branch,243 },244 Destination: gitopsdeploymentv1alpha1.ApplicationDestination{},245 Type: gitopsdeploymentv1alpha1.GitOpsDeploymentSpecType_Automated,246 },247 }248 return res, nil249}250// Ensure that the name of the GitOpsDeployment is always <= 64 characters251func sanitizeAppNameWithSuffix(appName string, suffix string) string {252 fullName := appName + suffix253 if len(fullName) < 64 {254 return fullName255 }256 sha256 := sha256.New()257 sha256.Write(([]byte)(appName))258 hashValBytes := (string)(sha256.Sum(nil))259 hashValStr := fmt.Sprintf("%x", hashValBytes)260 return hashValStr[0:32] + suffix261}262// SetupWithManager sets up the controller with the Manager.263func (r *ApplicationReconciler) SetupWithManager(mgr ctrl.Manager) error {264 return ctrl.NewControllerManagedBy(mgr).265 For(&applicationv1alpha1.Application{}).266 Complete(r)267}...
format_test.go
Source:format_test.go
...199 g.Eq(gop.Base64(bs), []byte(s))200 now := time.Now()201 g.Eq(gop.Time(now.Format(time.RFC3339Nano), 1234), now)202 g.Eq(gop.Duration("10m"), 10*time.Minute)203 g.Eq(gop.JSONStr(nil, "[1, 2]"), "[1, 2]")204 g.Eq(gop.JSONBytes(nil, "[1, 2]"), []byte("[1, 2]"))205}206func TestGetPrivateFieldErr(t *testing.T) {207 g := got.T(t)208 g.Panic(func() {209 gop.GetPrivateField(reflect.ValueOf(1), 0)210 })211 g.Panic(func() {212 gop.GetPrivateFieldByName(reflect.ValueOf(1), "test")213 })214}215func TestTypeName(t *testing.T) {216 g := got.T(t)217 type f float64...
convertors.go
Source:convertors.go
...39func Duration(s string) time.Duration {40 d, _ := time.ParseDuration(s)41 return d42}43// SymbolJSONStr for JSONStr44const SymbolJSONStr = "gop.JSONStr"45// JSONStr returns the raw46func JSONStr(v interface{}, raw string) string {47 return raw48}49// SymbolJSONBytes for JSONBytes50const SymbolJSONBytes = "gop.JSONBytes"51// JSONBytes returns the raw as []byte52func JSONBytes(v interface{}, raw string) []byte {53 return []byte(raw)54}...
JSONStr
Using AI Code Generation
1import "fmt"2import "gop"3func main() {4 fmt.Println(a.JSONStr())5}6import "encoding/json"7type A struct {8}9func (a *A) JSONStr() string {10 b, err := json.Marshal(a)11 if err != nil {12 return err.Error()13 }14 return string(b)15}16 /usr/lib/go/src/pkg/gop (from $GOROOT)17 /home/gopinath/go/src/pkg/gop (from $GOPATH)18import (19func main() {20 r := mux.NewRouter()21 r.HandleFunc("/", HomeHandler)22 http.Handle("/", r)23 http.ListenAndServe(":8080", nil)24}25func HomeHandler(w http.ResponseWriter, r *http.Request) {26 fmt.Fprintln(w, "Hello World!")27}28./webapp.go:7: imported and not used: "fmt"29./webapp.go:8: imported and not used: "github.com/gorilla/mux"30./webapp.go:9: imported and not used: "net/http"
JSONStr
Using AI Code Generation
1import (2func main() {3 fmt.Println(gop.JSONStr("Hello World!"))4}5import (6func main() {7 fmt.Println(gop.JSONStr("Hello World!"))8}
JSONStr
Using AI Code Generation
1import (2func main() {3 g := gop.New()4 g.Set("name", "Rohit Joshi")5 g.Set("age", 25)6 g.Set("city", "Mumbai")7 fmt.Println(g.JSONStr())8}9import (10func main() {11 g := gop.New()12 g.Set("name", "Rohit Joshi")13 g.Set("age", 25)14 g.Set("city", "Mumbai")15 fmt.Println(string(g.JSON()))16}17import (18func main() {19 g := gop.New()20 g.Set("name", "Rohit Joshi")21 g.Set("age", 25)22 g.Set("city", "Mumbai")23 j, err := g.JSON()24 if err != nil {25 fmt.Println(err)26 } else {27 fmt.Println(string(j))28 }29}30import (31func main() {32 g := gop.New()33 g.Set("name", "Rohit Joshi")34 g.Set("age", 25)35 g.Set("city", "Mumbai")36 j, err := g.JSON()37 if err != nil {38 fmt.Println(err)39 } else {40 fmt.Println(string(j))41 }42}43import (44func main() {
JSONStr
Using AI Code Generation
1import (2func main() {3 fmt.Println(gop.JSONStr(`{"name":"gop", "version":"0.1"}`))4}5import (6func main() {7 fmt.Println(gop.IsJSON(`{"name":"gop", "version":"0.1"}`))8}9import (10func main() {11 fmt.Println(gop.IsXML(`<name>gop</name>`))12}13import (14func main() {15 fmt.Println(gop.IsHTML(`<html><body><h1>gop</h1></body></html>`))16}17import (18func main() {19 fmt.Println(gop.IsYAML(`name: gop`))20}21import (22func main() {23 fmt.Println(gop.IsCSV(`name, gop`))24}25import (26func main() {27 fmt.Println(gop.IsSQL(`SELECT * FROM table`))28}29import (30func main() {
JSONStr
Using AI Code Generation
1import (2func main() {3 g := gop.New()4 g.LoadJSONStr(`{5 "address": {6 }7 }`)8 fmt.Println(g.JSONStr())9}10{11 "address": {12 }13}14import (15func main() {16 g := gop.New()17 g.LoadJSONFile("data.json")18 fmt.Println(g.JSONStr())19}20{21 "address": {22 }23}24import (25func main() {26 g := gop.New()27 g.LoadJSONStr(`{28 "address": {29 }30 }`)31 fmt.Println(g.Get("address.street"))32}
JSONStr
Using AI Code Generation
1import "fmt"2import "gop"3func main() {4 type Person struct {5 }6 p := Person{"Bob", 20}7 jstr := gop.JSONStr(p)8 fmt.Println(jstr)9}10import "fmt"11import "gop"12func main() {13 type Person struct {14 }15 p := Person{"Bob", 20}16 jstr := gop.JSONStr(p)17 fmt.Println(jstr)18}19import "fmt"20import "gop"21func main() {22 type Person struct {23 }24 p := Person{"Bob", 20}25 jstr := gop.JSONStr(p)26 fmt.Println(jstr)27}28import "fmt"29import "gop"30func main() {31 type Person struct {32 }33 p := Person{"Bob", 20}34 jstr := gop.JSONStr(p)35 fmt.Println(jstr)36}37import "fmt"38import "gop"39func main() {40 type Person struct {41 }42 p := Person{"Bob", 20}43 jstr := gop.JSONStr(p)44 fmt.Println(jstr)45}46import "fmt"47import "gop"48func main() {49 type Person struct {50 }51 p := Person{"Bob", 20}52 jstr := gop.JSONStr(p)53 fmt.Println(jstr)54}
JSONStr
Using AI Code Generation
1import (2func main() {3 g := gop.New()4 err := g.LoadFile("test.json")5 if err != nil {6 fmt.Println(err)7 os.Exit(1)8 }9 fmt.Println(g.JSONStr("foo.bar.baz"))10}11import (12func main() {13 g := gop.New()14 err := g.LoadFile("test.json")15 if err != nil {16 fmt.Println(err)17 os.Exit(1)18 }19 fmt.Println(g.JSONStr("foo.bar.baz"))20}21{22 "foo": {23 "bar": {24 }25 }26}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!