Best K6 code snippet using cloudapi.Error
service_http.go
Source:service_http.go
...14 "strings"15 "github.com/joyent/gosdc/cloudapi"16 "github.com/julienschmidt/httprouter"17)18// ErrorResponse defines a single HTTP error response.19type ErrorResponse struct {20 Code int21 Body string22 contentType string23 errorText string24 headers map[string]string25 cloudapi *CloudAPI26}27var (28 // ErrNotAllowed is returned when the request's method is not allowed29 ErrNotAllowed = &ErrorResponse{30 http.StatusMethodNotAllowed,31 "Method is not allowed",32 "text/plain; charset=UTF-8",33 "MethodNotAllowedError",34 nil,35 nil,36 }37 // ErrNotFound is returned when the requested resource is not found38 ErrNotFound = &ErrorResponse{39 http.StatusNotFound,40 "Resource Not Found",41 "text/plain; charset=UTF-8",42 "NotFoundError",43 nil,44 nil,45 }46 // ErrBadRequest is returned when the request is malformed or incorrect47 ErrBadRequest = &ErrorResponse{48 http.StatusBadRequest,49 "Malformed request url",50 "text/plain; charset=UTF-8",51 "BadRequestError",52 nil,53 nil,54 }55)56func (e *ErrorResponse) Error() string {57 return e.errorText58}59func (e *ErrorResponse) ServeHTTP(w http.ResponseWriter, r *http.Request) {60 if e.contentType != "" {61 w.Header().Set("Content-Type", e.contentType)62 }63 body := e.Body64 if e.headers != nil {65 for h, v := range e.headers {66 w.Header().Set(h, v)67 }68 }69 // workaround for https://code.google.com/p/go/issues/detail?id=445470 w.Header().Set("Content-Length", strconv.Itoa(len(body)))71 if e.Code != 0 {72 w.WriteHeader(e.Code)73 }74 if len(body) > 0 {75 w.Write([]byte(body))76 }77}78type cloudapiHandler struct {79 cloudapi *CloudAPI80 method func(m *CloudAPI, w http.ResponseWriter, r *http.Request, p httprouter.Params) error81}82func (h *cloudapiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, p httprouter.Params) {83 path := r.URL.Path84 // handle trailing slash in the path85 if strings.HasSuffix(path, "/") && path != "/" {86 ErrNotFound.ServeHTTP(w, r)87 return88 }89 err := h.method(h.cloudapi, w, r, p)90 if err == nil {91 return92 }93 var resp http.Handler94 resp, _ = err.(http.Handler)95 if resp == nil {96 resp = &ErrorResponse{97 http.StatusInternalServerError,98 `{"internalServerError":{"message":"Unkown Error",code:500}}`,99 "application/json",100 err.Error(),101 nil,102 h.cloudapi,103 }104 }105 resp.ServeHTTP(w, r)106}107func writeResponse(w http.ResponseWriter, code int, body []byte) {108 // workaround for https://code.google.com/p/go/issues/detail?id=4454109 w.Header().Set("Content-Length", strconv.Itoa(len(body)))110 w.WriteHeader(code)111 w.Write(body)112}113// sendJSON sends the specified response serialized as JSON.114func sendJSON(code int, resp interface{}, w http.ResponseWriter, r *http.Request) error {115 data, err := json.Marshal(resp)116 if err != nil {117 return err118 }119 w.Header().Set("Content-Type", "application/json")120 writeResponse(w, code, data)121 return nil122}123func processFilter(rawQuery string) map[string]string {124 var filters map[string]string125 if rawQuery != "" {126 filters = make(map[string]string)127 for _, filter := range strings.Split(rawQuery, "&") {128 filters[filter[:strings.Index(filter, "=")]] = filter[strings.Index(filter, "=")+1:]129 }130 }131 return filters132}133func (c *CloudAPI) handler(method func(m *CloudAPI, w http.ResponseWriter, r *http.Request, p httprouter.Params) error) httprouter.Handle {134 handler := &cloudapiHandler{c, method}135 return handler.ServeHTTP136}137// Keys138func (c *CloudAPI) handleListKeys(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {139 keys, err := c.ListKeys()140 if err != nil {141 return err142 }143 if keys == nil {144 keys = []cloudapi.Key{}145 }146 return sendJSON(http.StatusOK, keys, w, r)147}148func (c *CloudAPI) handleGetKey(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {149 key, err := c.GetKey(params.ByName("id"))150 if err != nil {151 return err // TODO: 404 if key not found152 }153 if key == nil {154 key = &cloudapi.Key{}155 }156 return sendJSON(http.StatusOK, key, w, r)157}158func (c *CloudAPI) handleCreateKey(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {159 opts := &cloudapi.CreateKeyOpts{}160 body, err := ioutil.ReadAll(r.Body)161 defer r.Body.Close()162 if err != nil {163 return err164 }165 if len(body) > 0 {166 if err := json.Unmarshal(body, opts); err != nil {167 return err168 }169 }170 key, err := c.CreateKey(opts.Name, opts.Key)171 if err != nil {172 return err173 }174 if key == nil {175 key = &cloudapi.Key{}176 }177 return sendJSON(http.StatusCreated, key, w, r)178}179func (c *CloudAPI) handleDeleteKey(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {180 err := c.DeleteKey(params.ByName("id"))181 if err != nil {182 return err // TODO: handle 404183 }184 return sendJSON(http.StatusNoContent, nil, w, r)185}186// images187func (c *CloudAPI) handleListImages(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {188 images, err := c.ListImages(processFilter(r.URL.RawQuery))189 if err != nil {190 return err191 }192 if images == nil {193 images = []cloudapi.Image{}194 }195 return sendJSON(http.StatusOK, images, w, r)196}197func (c *CloudAPI) handleGetImage(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {198 image, err := c.GetImage(params.ByName("id"))199 if err != nil {200 return err // TODO: 404201 }202 if image == nil {203 image = &cloudapi.Image{}204 }205 return sendJSON(http.StatusOK, image, w, r)206}207func (c *CloudAPI) handleCreateImageFromMachine(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {208 return ErrNotFound // TODO: implement209}210func (c *CloudAPI) handleDeleteImage(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {211 // TODO: implement c.DeleteImage212 // err := c.DeleteImage(params.ByName("id"))213 // if err != nil {214 // return err // TODO: 404215 // }216 // return sendJSON(http.StatusNoContent, nil, w, r)217 return ErrNotAllowed218}219// packages220func (c *CloudAPI) handleListPackages(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {221 pkgs, err := c.ListPackages(processFilter(r.URL.RawQuery))222 if err != nil {223 return err224 }225 if pkgs == nil {226 pkgs = []cloudapi.Package{}227 }228 return sendJSON(http.StatusOK, pkgs, w, r)229}230func (c *CloudAPI) handleGetPackage(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {231 pkg, err := c.GetPackage(params.ByName("id"))232 if err != nil {233 return err // TODO: 404234 }235 if pkg == nil {236 pkg = &cloudapi.Package{}237 }238 return sendJSON(http.StatusOK, pkg, w, r)239}240// machines241func (c *CloudAPI) handleListMachines(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {242 machines, err := c.ListMachines(processFilter(r.URL.RawQuery))243 if err != nil {244 return err245 }246 if machines == nil {247 machines = []*cloudapi.Machine{}248 }249 return sendJSON(http.StatusOK, machines, w, r)250}251func (c *CloudAPI) handleCountMachines(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {252 count, err := c.CountMachines()253 if err != nil {254 return err255 }256 return sendJSON(http.StatusOK, count, w, r)257}258func (c *CloudAPI) handleGetMachine(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {259 machine, err := c.GetMachine(params.ByName("id"))260 if err != nil {261 return err // TODO: 404262 }263 if machine == nil {264 machine = &cloudapi.Machine{}265 }266 return sendJSON(http.StatusOK, machine, w, r)267}268func (c *CloudAPI) handleCreateMachine(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {269 var (270 name string271 pkg string272 image string273 networks []string274 metadata = map[string]string{}275 tags = map[string]string{}276 )277 opts := map[string]interface{}{}278 body, err := ioutil.ReadAll(r.Body)279 defer r.Body.Close()280 if err != nil {281 return err282 }283 if len(body) == 0 {284 return ErrBadRequest285 }286 if err := json.Unmarshal(body, &opts); err != nil {287 return err288 }289 for k, v := range opts {290 if v == nil {291 continue292 }293 switch k {294 case "name":295 name = v.(string)296 case "package":297 pkg = v.(string)298 case "image":299 image = v.(string)300 case "networks":301 networks = []string{}302 for _, n := range v.([]interface{}) {303 networks = append(networks, n.(string))304 }305 default:306 if strings.HasPrefix(k, "tag.") {307 tags[k[4:]] = v.(string)308 continue309 }310 if strings.HasPrefix(k, "metadata.") {311 metadata[k[9:]] = v.(string)312 continue313 }314 }315 }316 machine, err := c.CreateMachine(name, pkg, image, networks, metadata, tags)317 if err != nil {318 return err319 }320 if machine == nil {321 machine = &cloudapi.Machine{}322 }323 return sendJSON(http.StatusCreated, machine, w, r)324}325func (c *CloudAPI) handleUpdateMachine(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {326 var (327 err error328 id = params.ByName("id")329 )330 switch r.URL.Query().Get("action") {331 case "stop":332 err = c.StopMachine(id)333 case "start":334 err = c.StartMachine(id)335 case "reboot":336 err = c.RebootMachine(id)337 case "resize":338 err = c.ResizeMachine(id, r.URL.Query().Get("package"))339 case "rename":340 err = c.RenameMachine(id, r.URL.Query().Get("name"))341 case "enable_firewall":342 err = c.EnableFirewallMachine(id)343 case "disable_firewall":344 err = c.DisableFirewallMachine(id)345 default:346 return ErrNotAllowed347 }348 if err != nil {349 return err350 }351 return sendJSON(http.StatusAccepted, nil, w, r)352}353func (c *CloudAPI) handleDeleteMachine(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {354 err := c.DeleteMachine(params.ByName("id"))355 if err != nil {356 return err // TODO: 404357 }358 return sendJSON(http.StatusNoContent, nil, w, r)359}360func (c *CloudAPI) handleMachineFirewallRules(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {361 rules, err := c.ListMachineFirewallRules(params.ByName("id"))362 if err != nil {363 return err // TODO: 404364 }365 if rules == nil {366 rules = []*cloudapi.FirewallRule{}367 }368 return sendJSON(http.StatusOK, rules, w, r)369}370// machine metadata371func (c *CloudAPI) handleGetMachineMetadata(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {372 metadata, err := c.GetMachineMetadata(params.ByName("id"))373 if err != nil {374 return err375 }376 return sendJSON(http.StatusOK, metadata, w, r)377}378func (c *CloudAPI) handleUpdateMachineMetadata(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {379 metadata := make(map[string]string)380 body, err := ioutil.ReadAll(r.Body)381 defer r.Body.Close()382 if err != nil {383 return err384 }385 err = json.Unmarshal(body, &metadata)386 if err != nil {387 return err388 }389 metadata, err = c.UpdateMachineMetadata(params.ByName("id"), metadata)390 if err != nil {391 return err392 }393 return sendJSON(http.StatusOK, metadata, w, r)394}395func (c *CloudAPI) handleDeleteMachineMetadata(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {396 err := c.DeleteMachineMetadata(params.ByName("id"), params.ByName("key"))397 if err != nil {398 return err399 }400 return sendJSON(http.StatusNoContent, nil, w, r)401}402func (c *CloudAPI) handleDeleteAllMachineMetadata(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {403 err := c.DeleteAllMachineMetadata(params.ByName("id"))404 if err != nil {405 return err406 }407 return sendJSON(http.StatusNoContent, nil, w, r)408}409// machine tags410func (c *CloudAPI) handleListMachineTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {411 tags, err := c.ListMachineTags(params.ByName("id"))412 if err != nil {413 return err414 }415 return sendJSON(http.StatusOK, tags, w, r)416}417func (c *CloudAPI) handleAddMachineTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {418 tags := make(map[string]string)419 body, err := ioutil.ReadAll(r.Body)420 defer r.Body.Close()421 if err != nil {422 return err423 }424 err = json.Unmarshal(body, &tags)425 if err != nil {426 return err427 }428 tags, err = c.AddMachineTags(params.ByName("id"), tags)429 if err != nil {430 return err431 }432 return sendJSON(http.StatusOK, tags, w, r)433}434func (c *CloudAPI) handleReplaceMachineTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {435 tags := make(map[string]string)436 body, err := ioutil.ReadAll(r.Body)437 defer r.Body.Close()438 if err != nil {439 return err440 }441 err = json.Unmarshal(body, &tags)442 if err != nil {443 return err444 }445 tags, err = c.ReplaceMachineTags(params.ByName("id"), tags)446 if err != nil {447 return err448 }449 return sendJSON(http.StatusOK, tags, w, r)450}451func (c *CloudAPI) handleDeleteMachineTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {452 err := c.DeleteMachineTags(params.ByName("id"))453 if err != nil {454 return err455 }456 return sendJSON(http.StatusNoContent, nil, w, r)457}458func (c *CloudAPI) handleDeleteMachineTag(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {459 err := c.DeleteMachineTag(params.ByName("id"), params.ByName("tag"))460 if err != nil {461 return err462 }463 return sendJSON(http.StatusNoContent, nil, w, r)464}465func (c *CloudAPI) handleGetMachineTag(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {466 tag, err := c.GetMachineTag(params.ByName("id"), params.ByName("tag"))467 if err != nil {468 return err469 }470 w.Header().Add("Content-Type", "text/plain")471 w.WriteHeader(http.StatusOK)472 w.Write([]byte(tag))473 return nil474}475// NICs476func (c *CloudAPI) handleListNICs(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {477 nics, err := c.ListNICs(params.ByName("id"))478 if err != nil {479 return err480 }481 return sendJSON(http.StatusOK, nics, w, r)482}483func (c *CloudAPI) handleGetNIC(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {484 nic, err := c.GetNIC(params.ByName("id"), params.ByName("mac"))485 if err != nil {486 return err487 }488 return sendJSON(http.StatusOK, nic, w, r)489}490type addNICOptions struct {491 Network string `json:"network"`492}493func (c *CloudAPI) handleAddNIC(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {494 opts := new(addNICOptions)495 body, err := ioutil.ReadAll(r.Body)496 if err != nil {497 return err498 }499 if len(body) == 0 {500 return ErrBadRequest501 }502 if err = json.Unmarshal(body, opts); err != nil {503 return err504 }505 nic, err := c.AddNIC(params.ByName("id"), opts.Network)506 if err != nil {507 return err508 }509 return sendJSON(http.StatusCreated, nic, w, r)510}511func (c *CloudAPI) handleRemoveNIC(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {512 err := c.RemoveNIC(params.ByName("id"), params.ByName("mac"))513 if err != nil {514 return err515 }516 return sendJSON(http.StatusNoContent, nil, w, r)517}518// firewall rules519func (c *CloudAPI) handleListFirewallRules(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {520 rules, err := c.ListFirewallRules()521 if err != nil {522 return err523 }524 if rules == nil {525 rules = []*cloudapi.FirewallRule{}526 }527 return sendJSON(http.StatusOK, rules, w, r)528}529func (c *CloudAPI) handleGetFirewallRule(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {530 rule, err := c.GetFirewallRule(params.ByName("id"))531 if err != nil {532 return err // TODO: 404533 }534 if rule == nil {535 rule = &cloudapi.FirewallRule{}536 }537 return sendJSON(http.StatusOK, rule, w, r)538}539func (c *CloudAPI) handleCreateFirewallRule(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {540 opts := new(cloudapi.CreateFwRuleOpts)541 body, err := ioutil.ReadAll(r.Body)542 if err != nil {543 return err544 }545 if len(body) == 0 {546 return ErrBadRequest547 }548 if err = json.Unmarshal(body, opts); err != nil {549 return err550 }551 rule, err := c.CreateFirewallRule(opts.Rule, opts.Enabled)552 if err != nil {553 return err554 }555 if rule == nil {556 rule = &cloudapi.FirewallRule{}557 }558 return sendJSON(http.StatusCreated, rule, w, r)559}560func (c *CloudAPI) handleUpdateFirewallRule(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {561 opts := new(cloudapi.CreateFwRuleOpts)562 body, err := ioutil.ReadAll(r.Body)563 if err != nil {564 return err565 }566 if len(body) == 0 {567 return ErrBadRequest568 }569 if err = json.Unmarshal(body, opts); err != nil {570 return err571 }572 rule, err := c.UpdateFirewallRule(params.ByName("id"), opts.Rule, opts.Enabled)573 if err != nil {574 return err // TODO: 404575 }576 if rule == nil {577 rule = new(cloudapi.FirewallRule)578 }579 return sendJSON(http.StatusOK, rule, w, r)580}581func (c *CloudAPI) handleDeleteFirewallRule(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {582 err := c.DeleteFirewallRule(params.ByName("id"))583 if err != nil {584 return err585 }586 return sendJSON(http.StatusNoContent, nil, w, r)587}588func (c *CloudAPI) handleEnableFirewallRule(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {589 rule, err := c.EnableFirewallRule(params.ByName("id"))590 if err != nil {591 return err // TODO: 404592 }593 if rule == nil {594 rule = new(cloudapi.FirewallRule)595 }596 return sendJSON(http.StatusOK, rule, w, r)597}598func (c *CloudAPI) handleDisableFirewallRule(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {599 rule, err := c.DisableFirewallRule(params.ByName("id"))600 if err != nil {601 return err // TODO: 404602 }603 if rule == nil {604 rule = new(cloudapi.FirewallRule)605 }606 return sendJSON(http.StatusOK, rule, w, r)607}608// Networks609func (c *CloudAPI) handleListNetworks(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {610 networks, err := c.ListNetworks()611 if err != nil {612 return err613 }614 if networks == nil {615 networks = []cloudapi.Network{}616 }617 return sendJSON(http.StatusOK, networks, w, r)618}619func (c *CloudAPI) handleGetNetwork(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {620 network, err := c.GetNetwork(params.ByName("id"))621 if err != nil {622 return err // TODO: 404623 }624 if network == nil {625 network = new(cloudapi.Network)626 }627 return sendJSON(http.StatusOK, network, w, r)628}629// Fabrics + VLANs and Networks630func (c *CloudAPI) handleListFabricVLANs(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {631 vlans, err := c.ListFabricVLANs()632 if err != nil {633 return err634 }635 return sendJSON(http.StatusOK, vlans, w, r)636}637func (c *CloudAPI) handleCreateFabricVLAN(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {638 body, err := ioutil.ReadAll(r.Body)639 if err != nil {640 return err641 }642 if len(body) == 0 {643 return ErrBadRequest644 }645 var opts cloudapi.FabricVLAN646 if err = json.Unmarshal(body, &opts); err != nil {647 return err648 }649 vlan, err := c.CreateFabricVLAN(opts)650 if err != nil {651 return err652 }653 return sendJSON(http.StatusCreated, vlan, w, r)654}655func (c *CloudAPI) handleGetFabricVLAN(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {656 id, err := strconv.Atoi(params.ByName("id"))657 if err != nil {658 return err659 }660 vlan, err := c.GetFabricVLAN(int16(id))661 if err != nil {662 return err663 }664 return sendJSON(http.StatusOK, vlan, w, r)665}666func (c *CloudAPI) handleUpdateFabricVLAN(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {667 body, err := ioutil.ReadAll(r.Body)668 if err != nil {669 return err670 }671 if len(body) == 0 {672 return ErrBadRequest673 }674 var opts cloudapi.FabricVLAN675 if err = json.Unmarshal(body, &opts); err != nil {676 return err677 }678 vlan, err := c.UpdateFabricVLAN(opts)679 if err != nil {680 return err681 }682 return sendJSON(http.StatusAccepted, vlan, w, r)683}684func (c *CloudAPI) handleDeleteFabricVLAN(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {685 id, err := strconv.Atoi(params.ByName("id"))686 if err != nil {687 return err688 }689 err = c.DeleteFabricVLAN(int16(id))690 if err != nil {691 return err692 }693 return sendJSON(http.StatusNoContent, nil, w, r)694}695func (c *CloudAPI) handleListFabricNetworks(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {696 id, err := strconv.Atoi(params.ByName("id"))697 if err != nil {698 return err699 }700 networks, err := c.ListFabricNetworks(int16(id))701 if err != nil {702 return err703 }704 return sendJSON(http.StatusOK, networks, w, r)705}706func (c *CloudAPI) handleCreateFabricNetwork(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {707 id, err := strconv.Atoi(params.ByName("id"))708 if err != nil {709 return err710 }711 body, err := ioutil.ReadAll(r.Body)712 if err != nil {713 return err714 }715 if len(body) == 0 {716 return ErrBadRequest717 }718 var opts cloudapi.CreateFabricNetworkOpts719 if err = json.Unmarshal(body, &opts); err != nil {720 return err721 }722 network, err := c.CreateFabricNetwork(int16(id), opts)723 if err != nil {724 return err725 }726 return sendJSON(http.StatusCreated, network, w, r)727}728func (c *CloudAPI) handleGetFabricNetwork(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {729 id, err := strconv.Atoi(params.ByName("id"))730 if err != nil {731 return err732 }733 network, err := c.GetFabricNetwork(int16(id), params.ByName("network"))734 if err != nil {735 return err736 }737 return sendJSON(http.StatusOK, network, w, r)738}739func (c *CloudAPI) handleDeleteFabricNetwork(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {740 id, err := strconv.Atoi(params.ByName("id"))741 if err != nil {742 return err743 }744 err = c.DeleteFabricNetwork(int16(id), params.ByName("network"))745 if err != nil {746 return err747 }748 return sendJSON(http.StatusNoContent, nil, w, r)749}750// ListServices handler751func (c *CloudAPI) handleGetServices(w http.ResponseWriter, r *http.Request, params httprouter.Params) error {752 services := map[string]string{753 "cloudapi": "https://us-west-1.api.example.com",754 }755 return sendJSON(http.StatusOK, services, w, r)756}757// Error responses758type NotFound struct{}759func (NotFound) ServeHTTP(w http.ResponseWriter, r *http.Request) {760 w.WriteHeader(http.StatusNotFound)761 w.Write([]byte("Resource Not Found"))762}763type MethodNotAllowed struct{}764func (MethodNotAllowed) ServeHTTP(w http.ResponseWriter, r *http.Request) {765 w.WriteHeader(http.StatusMethodNotAllowed)766 w.Write([]byte("Method is not allowed"))767}768// SetupHTTP attaches all the needed handlers to provide the HTTP API.769func (c *CloudAPI) SetupHTTP(mux *httprouter.Router) {770 baseRoute := "/" + c.ServiceInstance.UserAccount771 mux.NotFound = NotFound{}...
service.go
Source:service.go
...216 if key.Name == keyName {217 return &key, nil218 }219 }220 return nil, fmt.Errorf("Key %s not found", keyName)221}222func (c *CloudAPI) CreateKey(keyName, key string) (*cloudapi.Key, error) {223 if err := c.ProcessFunctionHook(c, keyName, key); err != nil {224 return nil, err225 }226 // check if key already exists or keyName already in use227 for _, k := range c.keys {228 if k.Name == keyName {229 return nil, fmt.Errorf("Key name %s already in use", keyName)230 }231 if k.Key == key {232 return nil, fmt.Errorf("Key %s already exists", key)233 }234 }235 newKey := cloudapi.Key{Name: keyName, Fingerprint: "", Key: key}236 c.keys = append(c.keys, newKey)237 return &newKey, nil238}239func (c *CloudAPI) DeleteKey(keyName string) error {240 if err := c.ProcessFunctionHook(c, keyName); err != nil {241 return err242 }243 for i, key := range c.keys {244 if key.Name == keyName {245 c.keys = append(c.keys[:i], c.keys[i+1:]...)246 return nil247 }248 }249 return fmt.Errorf("Key %s not found", keyName)250}251// Packages APIs252func (c *CloudAPI) ListPackages(filters map[string]string) ([]cloudapi.Package, error) {253 if err := c.ProcessFunctionHook(c, filters); err != nil {254 return nil, err255 }256 availablePackages := c.packages257 if filters != nil {258 for k, f := range filters {259 // check if valid filter260 if contains(packagesFilters, k) {261 pkgs := []cloudapi.Package{}262 // filter from availablePackages and add to pkgs263 for _, p := range availablePackages {264 if k == "name" && p.Name == f {265 pkgs = append(pkgs, p)266 } else if k == "memory" {267 i, err := strconv.Atoi(f)268 if err == nil && p.Memory == i {269 pkgs = append(pkgs, p)270 }271 } else if k == "disk" {272 i, err := strconv.Atoi(f)273 if err == nil && p.Disk == i {274 pkgs = append(pkgs, p)275 }276 } else if k == "swap" {277 i, err := strconv.Atoi(f)278 if err == nil && p.Swap == i {279 pkgs = append(pkgs, p)280 }281 } else if k == "version" && p.Version == f {282 pkgs = append(pkgs, p)283 } else if k == "vcpus" {284 i, err := strconv.Atoi(f)285 if err == nil && p.VCPUs == i {286 pkgs = append(pkgs, p)287 }288 } else if k == "group" && p.Group == f {289 pkgs = append(pkgs, p)290 }291 }292 availablePackages = pkgs293 }294 }295 }296 return availablePackages, nil297}298func (c *CloudAPI) GetPackage(packageName string) (*cloudapi.Package, error) {299 if err := c.ProcessFunctionHook(c, packageName); err != nil {300 return nil, err301 }302 for _, pkg := range c.packages {303 if pkg.Name == packageName {304 return &pkg, nil305 }306 if pkg.Id == packageName {307 return &pkg, nil308 }309 }310 return nil, fmt.Errorf("Package %s not found", packageName)311}312// Images APIs313func (c *CloudAPI) ListImages(filters map[string]string) ([]cloudapi.Image, error) {314 if err := c.ProcessFunctionHook(c, filters); err != nil {315 return nil, err316 }317 availableImages := c.images318 if filters != nil {319 for k, f := range filters {320 // check if valid filter321 if contains(imagesFilters, k) {322 imgs := []cloudapi.Image{}323 // filter from availableImages and add to imgs324 for _, i := range availableImages {325 if k == "name" && i.Name == f {326 imgs = append(imgs, i)327 } else if k == "os" && i.OS == f {328 imgs = append(imgs, i)329 } else if k == "version" && i.Version == f {330 imgs = append(imgs, i)331 } else if k == "public" && i.Public == f {332 imgs = append(imgs, i)333 } else if k == "state" && i.State == f {334 imgs = append(imgs, i)335 } else if k == "owner" && i.Owner == f {336 imgs = append(imgs, i)337 } else if k == "type" && i.Type == f {338 imgs = append(imgs, i)339 }340 }341 availableImages = imgs342 }343 }344 }345 return availableImages, nil346}347func (c *CloudAPI) GetImage(imageId string) (*cloudapi.Image, error) {348 if err := c.ProcessFunctionHook(c, imageId); err != nil {349 return nil, err350 }351 for _, image := range c.images {352 if image.Id == imageId {353 return &image, nil354 }355 }356 return nil, fmt.Errorf("Image %s not found", imageId)357}358// Machine APIs359func (c *CloudAPI) ListMachines(filters map[string]string) ([]*cloudapi.Machine, error) {360 if err := c.ProcessFunctionHook(c, filters); err != nil {361 return nil, err362 }363 availableMachines := c.machines364 if filters != nil {365 for k, f := range filters {366 // check if valid filter367 if contains(machinesFilters, k) {368 machines := []*cloudapi.Machine{}369 // filter from availableMachines and add to machines370 for _, m := range availableMachines {371 if k == "name" && m.Name == f {372 machines = append(machines, m)373 } else if k == "type" && m.Type == f {374 machines = append(machines, m)375 } else if k == "state" && m.State == f {376 machines = append(machines, m)377 } else if k == "image" && m.Image == f {378 machines = append(machines, m)379 } else if k == "memory" {380 i, err := strconv.Atoi(f)381 if err == nil && m.Memory == i {382 machines = append(machines, m)383 }384 } else if strings.HasPrefix(k, "tags.") {385 for t, v := range m.Tags {386 if t == k[strings.Index(k, ".")+1:] && v == f {387 machines = append(machines, m)388 }389 }390 }391 }392 availableMachines = machines393 }394 }395 }396 return availableMachines, nil397}398func (c *CloudAPI) CountMachines() (int, error) {399 if err := c.ProcessFunctionHook(c); err != nil {400 return 0, err401 }402 return len(c.machines), nil403}404func (c *CloudAPI) GetMachine(machineId string) (*cloudapi.Machine, error) {405 if err := c.ProcessFunctionHook(c, machineId); err != nil {406 return nil, err407 }408 for _, machine := range c.machines {409 if machine.Id == machineId {410 return machine, nil411 }412 }413 return nil, fmt.Errorf("Machine %s not found", machineId)414}415func (c *CloudAPI) CreateMachine(name, pkg, image string, metadata, tags map[string]string) (*cloudapi.Machine, error) {416 if err := c.ProcessFunctionHook(c, name, pkg, image); err != nil {417 return nil, err418 }419 machineId, err := localservices.NewUUID()420 if err != nil {421 return nil, err422 }423 mPkg, err := c.GetPackage(pkg)424 if err != nil {425 return nil, err426 }427 mImg, err := c.GetImage(image)428 if err != nil {429 return nil, err430 }431 publicIP := generatePublicIPAddress()432 newMachine := &cloudapi.Machine{433 Id: machineId,434 Name: name,435 Type: mImg.Type,436 State: "running",437 Memory: mPkg.Memory,438 Disk: mPkg.Disk,439 IPs: []string{publicIP, generatePrivateIPAddress()},440 Created: time.Now().Format("2013-11-26T19:47:13.448Z"),441 Package: pkg,442 Image: image,443 Metadata: metadata,444 Tags: tags,445 PrimaryIP: publicIP,446 }447 c.machines = append(c.machines, newMachine)448 return newMachine, nil449}450func (c *CloudAPI) StopMachine(machineId string) error {451 if err := c.ProcessFunctionHook(c, machineId); err != nil {452 return err453 }454 for _, machine := range c.machines {455 if machine.Id == machineId {456 machine.State = "stopped"457 machine.Updated = time.Now().Format("2013-11-26T19:47:13.448Z")458 return nil459 }460 }461 return fmt.Errorf("Machine %s not found", machineId)462}463func (c *CloudAPI) StartMachine(machineId string) error {464 if err := c.ProcessFunctionHook(c, machineId); err != nil {465 return err466 }467 for _, machine := range c.machines {468 if machine.Id == machineId {469 machine.State = "running"470 machine.Updated = time.Now().Format("2013-11-26T19:47:13.448Z")471 return nil472 }473 }474 return fmt.Errorf("Machine %s not found", machineId)475}476func (c *CloudAPI) RebootMachine(machineId string) error {477 if err := c.ProcessFunctionHook(c, machineId); err != nil {478 return err479 }480 for _, machine := range c.machines {481 if machine.Id == machineId {482 machine.State = "running"483 machine.Updated = time.Now().Format("2013-11-26T19:47:13.448Z")484 return nil485 }486 }487 return fmt.Errorf("Machine %s not found", machineId)488}489func (c *CloudAPI) ResizeMachine(machineId, packageName string) error {490 if err := c.ProcessFunctionHook(c, machineId, packageName); err != nil {491 return err492 }493 mPkg, err := c.GetPackage(packageName)494 if err != nil {495 return err496 }497 for _, machine := range c.machines {498 if machine.Id == machineId {499 machine.Package = packageName500 machine.Memory = mPkg.Memory501 machine.Disk = mPkg.Disk502 machine.Updated = time.Now().Format("2013-11-26T19:47:13.448Z")503 return nil504 }505 }506 return fmt.Errorf("Machine %s not found", machineId)507}508func (c *CloudAPI) RenameMachine(machineId, newName string) error {509 if err := c.ProcessFunctionHook(c, machineId, newName); err != nil {510 return err511 }512 for _, machine := range c.machines {513 if machine.Id == machineId {514 machine.Name = newName515 machine.Updated = time.Now().Format("2013-11-26T19:47:13.448Z")516 return nil517 }518 }519 return fmt.Errorf("Machine %s not found", machineId)520}521func (c *CloudAPI) ListMachineFirewallRules(machineId string) ([]*cloudapi.FirewallRule, error) {522 if err := c.ProcessFunctionHook(c, machineId); err != nil {523 return nil, err524 }525 fwRules := []*cloudapi.FirewallRule{}526 for _, r := range c.firewallRules {527 vm := "vm " + machineId528 if strings.Contains(r.Rule, vm) {529 fwRules = append(fwRules, r)530 }531 }532 return fwRules, nil533}534func (c *CloudAPI) EnableFirewallMachine(machineId string) error {535 if err := c.ProcessFunctionHook(c, machineId); err != nil {536 return err537 }538 c.machineFw[machineId] = true539 return nil540}541func (c *CloudAPI) DisableFirewallMachine(machineId string) error {542 if err := c.ProcessFunctionHook(c, machineId); err != nil {543 return err544 }545 c.machineFw[machineId] = false546 return nil547}548func (c *CloudAPI) DeleteMachine(machineId string) error {549 if err := c.ProcessFunctionHook(c, machineId); err != nil {550 return err551 }552 for i, machine := range c.machines {553 if machine.Id == machineId {554 if machine.State == "stopped" {555 c.machines = append(c.machines[:i], c.machines[i+1:]...)556 return nil557 } else {558 return fmt.Errorf("Cannot Delete machine %s, machine is not stopped.", machineId)559 }560 }561 }562 return fmt.Errorf("Machine %s not found", machineId)563}564// FirewallRule APIs565func (c *CloudAPI) ListFirewallRules() ([]*cloudapi.FirewallRule, error) {566 if err := c.ProcessFunctionHook(c); err != nil {567 return nil, err568 }569 return c.firewallRules, nil570}571func (c *CloudAPI) GetFirewallRule(fwRuleId string) (*cloudapi.FirewallRule, error) {572 if err := c.ProcessFunctionHook(c, fwRuleId); err != nil {573 return nil, err574 }575 for _, r := range c.firewallRules {576 if strings.EqualFold(r.Id, fwRuleId) {577 return r, nil578 }579 }580 return nil, fmt.Errorf("Firewall rule %s not found", fwRuleId)581}582func (c *CloudAPI) CreateFirewallRule(rule string, enabled bool) (*cloudapi.FirewallRule, error) {583 if err := c.ProcessFunctionHook(c, rule, enabled); err != nil {584 return nil, err585 }586 fwRuleId, err := localservices.NewUUID()587 if err != nil {588 return nil, fmt.Errorf("Error creating firewall rule: %q", err)589 }590 fwRule := &cloudapi.FirewallRule{Id: fwRuleId, Rule: rule, Enabled: enabled}591 c.firewallRules = append(c.firewallRules, fwRule)592 return fwRule, nil593}594func (c *CloudAPI) UpdateFirewallRule(fwRuleId, rule string, enabled bool) (*cloudapi.FirewallRule, error) {595 if err := c.ProcessFunctionHook(c, fwRuleId, rule, enabled); err != nil {596 return nil, err597 }598 for _, r := range c.firewallRules {599 if strings.EqualFold(r.Id, fwRuleId) {600 r.Rule = rule601 r.Enabled = enabled602 return r, nil603 }604 }605 return nil, fmt.Errorf("Firewall rule %s not found", fwRuleId)606}607func (c *CloudAPI) EnableFirewallRule(fwRuleId string) (*cloudapi.FirewallRule, error) {608 if err := c.ProcessFunctionHook(c, fwRuleId); err != nil {609 return nil, err610 }611 for _, r := range c.firewallRules {612 if strings.EqualFold(r.Id, fwRuleId) {613 r.Enabled = true614 return r, nil615 }616 }617 return nil, fmt.Errorf("Firewall rule %s not found", fwRuleId)618}619func (c *CloudAPI) DisableFirewallRule(fwRuleId string) (*cloudapi.FirewallRule, error) {620 if err := c.ProcessFunctionHook(c, fwRuleId); err != nil {621 return nil, err622 }623 for _, r := range c.firewallRules {624 if strings.EqualFold(r.Id, fwRuleId) {625 r.Enabled = false626 return r, nil627 }628 }629 return nil, fmt.Errorf("Firewall rule %s not found", fwRuleId)630}631func (c *CloudAPI) DeleteFirewallRule(fwRuleId string) error {632 if err := c.ProcessFunctionHook(c, fwRuleId); err != nil {633 return err634 }635 for i, r := range c.firewallRules {636 if strings.EqualFold(r.Id, fwRuleId) {637 c.firewallRules = append(c.firewallRules[:i], c.firewallRules[i+1:]...)638 return nil639 }640 }641 return fmt.Errorf("Firewall rule %s not found", fwRuleId)642}643func (c *CloudAPI) ListFirewallRuleMachines(fwRuleId string) ([]*cloudapi.Machine, error) {644 if err := c.ProcessFunctionHook(c, fwRuleId); err != nil {645 return nil, err646 }647 return c.machines, nil648}649// Networks API650func (c *CloudAPI) ListNetworks() ([]cloudapi.Network, error) {651 if err := c.ProcessFunctionHook(c); err != nil {652 return nil, err653 }654 return c.networks, nil655}656func (c *CloudAPI) GetNetwork(networkId string) (*cloudapi.Network, error) {657 if err := c.ProcessFunctionHook(c, networkId); err != nil {658 return nil, err659 }660 for _, n := range c.networks {661 if strings.EqualFold(n.Id, networkId) {662 return &n, nil663 }664 }665 return nil, fmt.Errorf("Network %s not found", networkId)666}...
Error
Using AI Code Generation
1import (2func main() {3 config, err := edgegrid.Init("~/.edgerc", "default")4 if err != nil {5 log.Fatal(err)6 }7 client := edgegrid.Client{8 }9 cloudapi := cloudapi.Client{10 }11 httpClient := &http.Client{12 }13 httpClient2 := &http.Client{14 }15 httpClient3 := &http.Client{16 }17 httpClient4 := &http.Client{18 }
Error
Using AI Code Generation
1import (2func main() {3 sess := session.New()4 service := services.GetAccountService(sess)5 err := service.Id(1234).Error()6 if err != nil {7 fmt.Println(err)8 }9}10import (11func main() {12 sess := session.New()13 service := services.GetAccountService(sess)14 err := service.SetId(1234).Error()15 if err != nil {16 fmt.Println(err)17 }18}
Error
Using AI Code Generation
1import (2func main() {3 sess, err := session.New()4 if err != nil {5 log.Fatal(err)6 }7 clusterClient, err := containerv1.New(sess)8 if err != nil {9 log.Fatal(err)10 }11 cluster, err := clusterClient.Clusters().GetCluster("cluster-id")12 if err != nil {13 fmt.Println(err.Error())14 }15 fmt.Println(cluster)16}17{"code":"404","error":"Cluster not found","description":"Cluster not found"}18import (19type Error struct {20}21func main() {22 sess, err := session.New()23 if err != nil {24 log.Fatal(err)25 }26 clusterClient, err := containerv1.New(sess)27 if err != nil {28 log.Fatal(err)29 }30 cluster, err := clusterClient.Clusters().GetCluster("cluster-id")31 if err != nil {32 json.Unmarshal([]byte(err.Error()), &e)33 fmt.Println(e.Description)34 }35 fmt.Println(cluster)36}
Error
Using AI Code Generation
1import (2func main() {3 sess := session.New()4 client := services.GetAccountService(sess)5 account, err := client.Mask("id;firstName;lastName;companyName;email").GetObject()6 if err != nil {7 fmt.Println("Error: ", err)8 }9 fmt.Println("Account: ", account)10}11import (12func main() {13 sess := session.New()14 client := services.GetAccountService(sess)15 account, err := client.Mask("id;firstName;lastName;companyName;email").GetObject()16 if err != nil {17 fmt.Println("Error: ", err.Error())18 }19 fmt.Println("Account: ", account)20}
Error
Using AI Code Generation
1import (2func main() {3 t := terminal.NewStdUI()4 t.Error("Error occurred")5}6import (7func main() {8 t := terminal.NewStdUI()9 t.Info("Info")10}11import (12func main() {13 t := terminal.NewStdUI()14 t.Print("Print")15}16import (17func main() {18 t := terminal.NewStdUI()19 t.Say("Say")20}21import (22func main() {23 t := terminal.NewStdUI()24 t.Warn("Warn")25}26import (27func main() {28 t := terminal.NewStdUI()29 t.Write([]byte("Write"))30}31import (32func main() {33 t := terminal.NewStdUI()34 t.Write([]byte("Write"))35}36import (
Error
Using AI Code Generation
1import (2func main() {3 api.SetError("Test Error Message")4 fmt.Println(api.Error())5}6import (7func main() {8 api.SetError("Test Error Message")9 fmt.Println(api.Error())10}11type CloudApi struct {12}13func (api *CloudApi) SetError(error string) {14}15func (api *CloudApi) Error() string {16}17import (18func TestError(t *testing.T) {19 api.SetError("Test Error Message")20 if api.Error() != "Test Error Message" {21 t.Error("Expected 'Test Error Message', got ", api.Error())22 }23}24import (25func main() {26 api.SetError("Test Error Message")27 fmt.Println(api.Error())28}29import (30func TestError(t *testing.T) {31 api.SetError("Test Error Message")32 if api.Error() != "Test Error Message" {33 t.Error("Expected 'Test Error Message', got ", api.Error())34 }35}
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!!