Best Go-testdeep code snippet using td.getString
import_smithy.go
Source:import_smithy.go
1package smithy2import (3 "fmt"4 "os"5 "path/filepath"6 "strings"7 "github.com/boynton/data"8 "github.com/boynton/sadl"9 smithylib "github.com/boynton/smithy"10)11const UnspecifiedNamespace = "example"12const UnspecifiedVersion = "0.0"13// set to true to prevent enum traits that have only values from ever becoming actul enum objects.14var StringValuesNeverEnum bool = false15func IsValidFile(path string) bool {16 if strings.HasSuffix(path, ".smithy") {17 return true18 }19 if strings.HasSuffix(path, ".json") {20 _, err := smithylib.LoadAST(path)21 return err == nil22 }23 return false24}25func Import(paths []string, conf *sadl.Data) (*sadl.Model, error) {26 var err error27 name := conf.GetString("name")28 namespace := conf.GetString("namespace")29 if namespace == "" {30 conf.Put("namespace", UnspecifiedNamespace)31 }32 var tags []string //fir filtering, if non-nil33 model, err := AssembleModel(paths, tags)34 if err != nil {35 return nil, err36 }37 conf.Put("name", name)38 return ToSadl(model, conf)39}40/*41func (model *Model) addShape(absoluteName string, shape *Shape) {42 prefix := model.namespace + "#"43 prefixLen := len(prefix)44 if strings.HasPrefix(absoluteName, prefix) {45 if _, ok := model.ast.Shapes[absoluteName]; !ok {46 model.ast.Shapes[absoluteName] = shape47 }48 kk := absoluteName[prefixLen:]49 model.shapes[kk] = shape50 if shape.Type == "operation" {51 if shape.Input != nil {52 fmt.Println(sadl.Pretty(shape), prefixLen)53 iok := shape.Input.Target[prefixLen:]54 model.ioParams[iok] = shape.Input.Target55 }56 if shape.Output != nil {57 iok := shape.Output.Target[prefixLen:]58 model.ioParams[iok] = shape.Output.Target59 }60 }61 }62}63func NewModel(ast *AST) *Model {64 model := &Model{65 ast: ast,66 }67 model.shapes = make(map[string]*Shape, 0)68 model.ioParams = make(map[string]string, 0)69 model.namespace, model.name, model.version = ast.NamespaceAndServiceVersion()70 if model.name == "" {71 s := sadl.GetString(ast.Metadata, "name")72 if s != "" {73 model.name = s74 }75 }76 for k, v := range ast.Shapes {77 model.addShape(k, v)78 }79 return model80}81*/82type Importer struct {83 name string84 namespace string85 ast *smithylib.AST86 ioParams map[string]*smithylib.Shape87 schema *sadl.Schema88}89func ToSadl(ast *smithylib.AST, conf *sadl.Data) (*sadl.Model, error) {90 i := &Importer{91 ast: ast,92 ioParams: make(map[string]*smithylib.Shape, 0),93 }94 name := conf.GetString("name")95 if name != "" {96 i.name = name97 } else {98 s := ast.Metadata.GetString("name")99 if s != "" {100 i.name = s101 // delete(ast.Metadata, "name")102 }103 }104 service := conf.GetString("service")105 namespace := conf.GetString("namespace")106 base := conf.GetString("base")107 if namespace != UnspecifiedNamespace {108 i.namespace = namespace109 }110 annos := make(map[string]string, 0)111 if ast.Metadata != nil {112 for _, k := range ast.Metadata.Keys() {113 if k != "name" {114 s := sadl.AsString(ast.Metadata.Get(k))115 if k == "base" {116 annos[k] = s117 } else {118 annos["x_"+k] = s119 }120 }121 }122 }123 // annos["x_smithy_version"] = model.ast.Version124 schema := &sadl.Schema{125 Name: name,126 Namespace: namespace,127 Sadl: sadl.Version,128 Annotations: annos,129 Base: base,130 }131 //capture? ast.Smithy132 if schema.Namespace == UnspecifiedNamespace {133 schema.Namespace = ""134 }135 if schema.Version == UnspecifiedVersion {136 schema.Version = ""137 }138 i.schema = schema139 serviceName := ""140 serviceVersion := ""141 for _, shapeName := range ast.Shapes.Keys() {142 shapeDef := ast.Shapes.Get(shapeName)143 if shapeDef.Type == "service" {144 if service != "" {145 if shapeName != service {146 continue147 }148 } else {149 if serviceName != "" {150 return nil, fmt.Errorf("SADL only supports one service per model (%s, %s)", serviceName, shapeName)151 }152 }153 serviceName = shapeName154 serviceVersion = shapeDef.Version155 } else if shapeDef.Type == "operation" {156 if shapeDef.Input != nil {157 i.ioParams[shapeDef.Input.Target] = i.ast.GetShape(shapeDef.Input.Target)158 }159 if shapeDef.Output != nil {160 i.ioParams[shapeDef.Output.Target] = i.ast.GetShape(shapeDef.Output.Target)161 }162 }163 }164 if schema.Name == "" {165 schema.Name = stripNamespace(serviceName)166 }167 if schema.Version == "" {168 schema.Version = serviceVersion169 }170 if schema.Base == "" && schema.Version != "" {171 schema.Base = "/" + schema.Version172 }173 for _, k := range ast.Shapes.Keys() {174 v := ast.Shapes.Get(k)175 if v.Type != "service" || k == serviceName {176 i.importShape(k, v)177 }178 }179 return sadl.NewModel(schema)180}181func (i *Importer) importShape(shapeName string, shapeDef *smithylib.Shape) {182 if _, ok := i.ioParams[shapeName]; ok {183 return184 }185 switch shapeDef.Type {186 case "byte", "short", "integer", "long", "float", "double", "bigInteger", "bigDecimal":187 i.importNumericShape(shapeDef.Type, shapeName, shapeDef)188 case "string":189 i.importStringShape(shapeName, shapeDef)190 case "timestamp":191 i.importTimestampShape(shapeName, shapeDef)192 case "boolean":193 i.importBooleanShape(shapeName, shapeDef)194 case "list":195 i.importListShape(shapeName, shapeDef, false)196 case "set":197 i.importListShape(shapeName, shapeDef, true)198 case "map":199 i.importMapShape(shapeName, shapeDef)200 case "structure":201 i.importStructureShape(shapeName, shapeDef)202 case "union":203 i.importUnionShape(shapeName, shapeDef)204 case "blob":205 i.importBlobShape(shapeName, shapeDef)206 case "enum":207 i.importEnumShape(shapeName, shapeDef)208 case "service":209 //FIX schema.Name = shapeName210 case "operation":211 i.importOperationShape(shapeName, shapeDef)212 case "resource":213 i.importResourceShape(shapeName, shapeDef)214 default:215 fmt.Println("fix me, unhandled shape type: " + shapeDef.Type)216 panic("whoa")217 }218}219func escapeComment(doc string) string {220 lines := strings.Split(doc, "\n")221 if len(lines) == 1 {222 return doc223 }224 for i, line := range lines {225 lines[i] = strings.Trim(line, " ")226 }227 // return strings.Replace(strings.Replace(doc, "\n", " ", -1), " ", " ", -1)228 return strings.Join(lines, "\n")229}230func (i *Importer) importNumericShape(smithyType string, shapeName string, shape *smithylib.Shape) {231 sadlName := stripNamespace(shapeName)232 td := &sadl.TypeDef{233 Name: sadlName,234 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),235 Annotations: i.importTraitsAsAnnotations(nil, shape.Traits),236 }237 switch smithyType {238 case "byte":239 td.Type = "Int8"240 case "short":241 td.Type = "Int16"242 case "integer":243 td.Type = "Int32"244 case "long":245 td.Type = "Int64"246 case "float":247 td.Type = "Float32"248 case "double":249 td.Type = "Float64"250 case "bigInteger":251 td.Type = "Decimal"252 td.Annotations = WithAnnotation(td.Annotations, "x_integer", "true")253 case "bigDecimal":254 td.Type = "Decimal"255 default:256 panic("whoops")257 }258 if l := shape.Traits.GetMap("smithy.api#range"); l != nil {259 tmp := sadl.GetDecimal(l, "min")260 if tmp != nil {261 td.Min = tmp262 }263 tmp = sadl.GetDecimal(l, "max")264 if tmp != nil {265 td.Max = tmp266 }267 }268 i.schema.Types = append(i.schema.Types, td)269}270func (i *Importer) importStringShape(shapeName string, shape *smithylib.Shape) {271 sadlName := stripNamespace(shapeName)272 if sadlName == "UUID" {273 fmt.Println("UUID shape name:", shapeName)274 //UUID is already a builtin SADL type275 return276 }277 if i.importEnum(shapeName, shape) {278 return279 }280 td := &sadl.TypeDef{281 Name: sadlName,282 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),283 }284 pat := shape.Traits.GetString("smithy.api#pattern")285 if pat == "([a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8})" {286 td.Type = "UUID"287 } else {288 td.Type = "String"289 td.Pattern = pat290 if l := shape.Traits.GetMap("smithy.api#length"); l != nil {291 tmp := sadl.GetInt64(l, "min")292 if tmp != 0 {293 td.MinSize = &tmp294 }295 tmp = sadl.GetInt64(l, "max")296 if tmp != 0 {297 td.MaxSize = &tmp298 }299 }300 lst := shape.Traits.GetArray("smithy.api#enum")301 if lst != nil {302 var values []string303 for _, v := range lst {304 m := sadl.AsMap(v)305 s := sadl.GetString(m, "value")306 values = append(values, s)307 }308 td.Values = values309 }310 }311 i.schema.Types = append(i.schema.Types, td)312}313func isSmithyRecommendedEnumName(s string) bool {314 if s == "" {315 return false316 }317 for i, ch := range s {318 if i == 0 {319 if !sadl.IsUppercaseLetter(ch) {320 return false321 }322 } else {323 if !(sadl.IsUppercaseLetter(ch) || sadl.IsDigit(ch) || ch == '_') {324 return false325 }326 }327 }328 return true329}330func (i *Importer) importEnum(shapeName string, shape *smithylib.Shape) bool {331 lst := shape.Traits.GetArray("smithy.api#enum")332 if lst == nil {333 return false334 }335 var elements []*sadl.EnumElementDef336 isEnum := false337 couldBeEnum := false338 for _, v := range lst {339 m := sadl.AsMap(v)340 sym := sadl.GetString(m, "name")341 if sym == "" {342 if StringValuesNeverEnum {343 return false344 }345 sym = sadl.GetString(m, "value")346 if !isSmithyRecommendedEnumName(sym) {347 return false348 }349 }350 element := &sadl.EnumElementDef{351 Symbol: sym,352 Comment: sadl.GetString(m, "documentation"),353 }354 //tags -> annotations?355 elements = append(elements, element)356 }357 if !isEnum {358 if !couldBeEnum { //might want a preference on this, if the values happen to follow symbol rules now, but really are values359 return false360 }361 }362 sadlName := stripNamespace(shapeName)363 td := &sadl.TypeDef{364 Name: sadlName,365 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),366 }367 td.Type = "Enum"368 td.Elements = elements369 i.schema.Types = append(i.schema.Types, td)370 return true371}372func (i *Importer) importTimestampShape(shapeName string, shape *smithylib.Shape) {373 sadlName := stripNamespace(shapeName)374 td := &sadl.TypeDef{375 Name: sadlName,376 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),377 Annotations: i.importTraitsAsAnnotations(nil, shape.Traits),378 }379 td.Type = "Timestamp"380 i.schema.Types = append(i.schema.Types, td)381}382func (i *Importer) importBlobShape(shapeName string, shape *smithylib.Shape) {383 sadlName := stripNamespace(shapeName)384 td := &sadl.TypeDef{385 Name: sadlName,386 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),387 }388 td.Type = "Bytes"389 if l := shape.Traits.GetMap("smithy.api#length"); l != nil {390 tmp := sadl.GetInt64(l, "min")391 if tmp != 0 {392 td.MinSize = &tmp393 }394 tmp = sadl.GetInt64(l, "max")395 if tmp != 0 {396 td.MaxSize = &tmp397 }398 }399 i.schema.Types = append(i.schema.Types, td)400}401func (i *Importer) importBooleanShape(shapeName string, shape *smithylib.Shape) {402 sadlName := stripNamespace(shapeName)403 td := &sadl.TypeDef{404 Name: sadlName,405 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),406 Annotations: i.importTraitsAsAnnotations(nil, shape.Traits),407 }408 td.Type = "Boolean"409 i.schema.Types = append(i.schema.Types, td)410}411func (i *Importer) importTraitsAsAnnotations(annos map[string]string, traits *data.Object) map[string]string {412 for _, k := range traits.Keys() {413 v := traits.Get(k)414 switch k {415 case "smithy.api#error":416 annos = WithAnnotation(annos, "x_"+stripNamespace(k), sadl.AsString(v))417 case "smithy.api#httpError":418 annos = WithAnnotation(annos, "x_"+stripNamespace(k), fmt.Sprintf("%v", v))419 case "smithy.api#httpPayload", "smithy.api#httpLabel", "smithy.api#httpQuery", "smithy.api#httpHeader":420 /* ignore, implicit in SADL */421 case "smithy.api#required", "smithy.api#documentation", "smithy.api#range", "smithy.api#length":422 /* ignore, implicit in SADL */423 case "smithy.api#tags":424 annos = WithAnnotation(annos, "x_"+stripNamespace(k), strings.Join(sadl.AsStringArray(v), ","))425 case "smithy.api#readonly", "smithy.api#idempotent", "smithy.api#sensitive", "smithy.api#box":426 // annos = WithAnnotation(annos, "x_"+stripNamespace(k), "true")427 case "smithy.api#http":428 /* ignore, handled elsewhere */429 case "smithy.api#timestampFormat", "smithy.api#enumValue":430 annos = WithAnnotation(annos, "x_"+stripNamespace(k), sadl.AsString(v))431 case "smithy.api#deprecated":432 //message433 //since434 dv := sadl.AsMap(v)435 annos = WithAnnotation(annos, "x_deprecated", "true")436 msg := sadl.GetString(dv, "message")437 if msg != "" {438 annos = WithAnnotation(annos, "x_deprecated_message", msg)439 }440 since := sadl.GetString(dv, "since")441 if since != "" {442 annos = WithAnnotation(annos, "x_deprecated_since", since)443 }444 case "smithy.api#paginated":445 dv := sadl.AsMap(v)446 inputToken := sadl.AsString(dv["inputToken"])447 outputToken := sadl.AsString(dv["outputToken"])448 pageSize := sadl.AsString(dv["pageSize"])449 items := sadl.AsString(dv["items"])450 s := fmt.Sprintf("inputToken=%s,outputToken=%s,pageSize=%s,items=%s", inputToken, outputToken, pageSize, items)451 annos = WithAnnotation(annos, "x_paginated", s)452 case "aws.protocols#restJson1":453 //ignore454 case "smithy.api#examples":455 //ignore for now456 default:457 tshape := i.ast.GetShape(k)458 if tshape != nil {459 tm := tshape.Traits.GetMap("smithy.api#trait")460 if tm != nil {461 fmt.Println("tshape:", k, tm)462 //FIX ME463 //I don't really have a place to put non-string annotations (note how I stuff string annos into "x_name").464 //So I really need arbitrary annotations values to do this. Note also: need multiple ns support!465 } else {466 fmt.Println("Unhandled trait:", k, " =", sadl.Pretty(v))467 panic("here: " + k)468 }469 } else {470 if strings.HasPrefix(k, "smithy.api#") {471 fmt.Println("Unhandled trait:", k, " =", sadl.Pretty(v))472 panic("here: " + k)473 } //else ignore474 }475 }476 }477 return annos478}479func (i *Importer) importEnumShape(shapeName string, shape *smithylib.Shape) {480 sadlName := stripNamespace(shapeName)481 td := &sadl.TypeDef{482 Name: sadlName,483 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),484 Annotations: i.importTraitsAsAnnotations(nil, shape.Traits),485 }486 td.Type = "Enum"487 // prefix := model.namespace + "#"488 var elements []*sadl.EnumElementDef489 for _, memberName := range shape.Members.Keys() {490 member := shape.Members.Get(memberName)491 ee := &sadl.EnumElementDef{492 Symbol: memberName,493 Comment: escapeComment(member.Traits.GetString("smithy.api#documentation")),494 Annotations: i.importTraitsAsAnnotations(nil, member.Traits),495 }496 elements = append(elements, ee)497 }498 td.Type = "Enum"499 td.Elements = elements500 i.schema.Types = append(i.schema.Types, td)501}502func (i *Importer) importUnionShape(shapeName string, shape *smithylib.Shape) {503 sadlName := stripNamespace(shapeName)504 td := &sadl.TypeDef{505 Name: sadlName,506 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),507 Annotations: i.importTraitsAsAnnotations(nil, shape.Traits),508 }509 td.Type = "Union"510 // prefix := model.namespace + "#"511 for _, memberName := range shape.Members.Keys() {512 member := shape.Members.Get(memberName)513 // if memberName != member.Target {514 vd := &sadl.UnionVariantDef{515 Name: memberName,516 Comment: escapeComment(member.Traits.GetString("smithy.api#documentation")),517 Annotations: i.importTraitsAsAnnotations(nil, member.Traits),518 }519 vd.Type = i.shapeRefToTypeRef(member.Target)520 /*521 m := member.Target522 if strings.HasPrefix(m, prefix) {523 m = member.Target[len(prefix):]524 }525 if m != memberName {526 fmt.Printf("member: %q, target: %q, m: %q\n", memberName, member.Target, m)527 panic("fixme: named union variants")528 }529 */530 // }531 // td.Variants = append(td.Variants, model.shapeRefToTypeRef(schema, member.Target))532 td.Variants = append(td.Variants, vd)533 }534 i.schema.Types = append(i.schema.Types, td)535}536func (i *Importer) importStructureShape(shapeName string, shape *smithylib.Shape) {537 //unless...no httpTraits, in which case is should equivalent to a payload description538 if _, ok := i.ioParams[shapeName]; ok {539 shape := i.ast.GetShape(shapeName)540 for _, k := range shape.Members.Keys() {541 fval := shape.Members.Get(k)542 if fval.Traits.GetBool("smithy.api#httpLabel") {543 return544 }545 if fval.Traits.GetBool("smithy.api#httpPayload") {546 return547 }548 if fval.Traits.GetString("smithy.api#httpQuery") != "" {549 return550 }551 }552 }553 sadlName := stripNamespace(shapeName)554 td := &sadl.TypeDef{555 Name: sadlName,556 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),557 Annotations: i.importTraitsAsAnnotations(nil, shape.Traits),558 }559 td.Type = "Struct"560 var fields []*sadl.StructFieldDef561 for _, memberName := range shape.Members.Keys() {562 member := shape.Members.Get(memberName)563 fd := &sadl.StructFieldDef{564 Name: memberName,565 Comment: escapeComment(member.Traits.GetString("smithy.api#documentation")),566 Annotations: i.importTraitsAsAnnotations(nil, member.Traits),567 Required: member.Traits.GetBool("smithy.api#required"),568 }569 fd.Type = i.shapeRefToTypeRef(member.Target)570 if member.Traits.GetBool("smithy.api#required") {571 fd.Required = true572 }573 fields = append(fields, fd)574 }575 td.Fields = fields576 i.schema.Types = append(i.schema.Types, td)577}578func (i *Importer) importListShape(shapeName string, shape *smithylib.Shape, unique bool) {579 sadlName := stripNamespace(shapeName)580 td := &sadl.TypeDef{581 Name: sadlName,582 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),583 }584 td.Type = "Array"585 td.Items = i.shapeRefToTypeRef(shape.Member.Target)586 tmp := shape.Traits.GetInt64("smithy.api#min")587 if tmp != 0 {588 td.MinSize = &tmp589 }590 tmp = shape.Traits.GetInt64("smithy.api#max")591 if tmp != 0 {592 td.MaxSize = &tmp593 }594 if unique {595 td.Annotations = WithAnnotation(td.Annotations, "x_unique", "true")596 }597 i.schema.Types = append(i.schema.Types, td)598}599func (i *Importer) importMapShape(shapeName string, shape *smithylib.Shape) {600 sadlName := stripNamespace(shapeName)601 td := &sadl.TypeDef{602 Name: sadlName,603 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),604 }605 td.Type = "Map"606 td.Keys = i.shapeRefToTypeRef(shape.Key.Target)607 td.Items = i.shapeRefToTypeRef(shape.Value.Target)608 tmp := shape.Traits.GetInt64("smithy.api#min")609 if tmp != 0 {610 td.MinSize = &tmp611 }612 tmp = shape.Traits.GetInt64("smithy.api#max")613 if tmp != 0 {614 td.MaxSize = &tmp615 }616 i.schema.Types = append(i.schema.Types, td)617}618func (i *Importer) ensureLocalNamespace(id string) string {619 if strings.Index(id, "#") < 0 {620 return id //already local621 }622 prefix := i.namespace + "#"623 if strings.HasPrefix(id, prefix) {624 return id[len(prefix):]625 }626 return ""627}628func (i *Importer) shapeRefToTypeRef(shapeRef string) string {629 typeRef := shapeRef630 switch typeRef {631 case "smithy.api#Blob", "Blob":632 return "Bytes"633 case "smithy.api#Boolean", "Boolean":634 return "Bool"635 case "smithy.api#String", "String":636 return "String"637 case "smithy.api#Byte", "Byte":638 return "Int8"639 case "smithy.api#Short", "Short":640 return "Int16"641 case "smithy.api#Integer", "Integer":642 return "Int32"643 case "smithy.api#Long", "Long":644 return "Int64"645 case "smithy.api#Float", "Float":646 return "Float32"647 case "smithy.api#Double", "Double":648 return "Float64"649 case "smithy.api#BigInteger", "BigInteger":650 return "Decimal" //lossy!651 case "smithy.api#BigDecimal", "BigDecimal":652 return "Decimal"653 case "smithy.api#Timestamp", "Timestamp":654 return "Timestamp"655 case "smithy.api#Document", "Document":656 return "Struct" //todo: introduce a separate type for open structs.657 default:658 if true {659 typeRef = stripNamespace(typeRef)660 } else {661 ltype := i.ensureLocalNamespace(typeRef)662 if ltype == "" {663 panic("external namespace type reference not supported: " + typeRef)664 }665 typeRef = ltype666 }667 }668 return typeRef669}670func (i *Importer) importResourceShape(shapeName string, shape *smithylib.Shape) {671 //to do: preserve the resource info as tags on the operations672}673func (i *Importer) importOperationShape(shapeName string, shape *smithylib.Shape) {674 var method, uri string675 var code int676 if ht := shape.Traits.GetObject("smithy.api#http"); ht != nil {677 method = ht.GetString("method")678 uri = ht.GetString("uri")679 code = ht.GetInt("code")680 }681 var inType string682 var inShapeName string683 if shape.Input != nil {684 inShapeName = shape.Input.Target685 inType = i.shapeRefToTypeRef(inShapeName)686 }687 var outType string688 var outShapeName string689 if shape.Output != nil {690 outShapeName = shape.Output.Target691 outType = i.shapeRefToTypeRef(outShapeName)692 }693 reqType := sadl.Capitalize(shapeName) + inputSuffix694 resType := sadl.Capitalize(shapeName) + outputSuffix695 if opexes := shape.Traits.GetArray("smithy.api#examples"); opexes != nil {696 for _, opexr := range opexes {697 if opex, ok := opexr.(map[string]interface{}); ok {698 title := sadl.GetString(opex, "title")699 if input, ok := opex["input"]; ok {700 ex := &sadl.ExampleDef{701 Target: reqType,702 Name: title,703 Comment: sadl.GetString(opex, "documentation"),704 Example: input,705 }706 i.schema.Examples = append(i.schema.Examples, ex)707 }708 if output, ok := opex["output"]; ok {709 ex := &sadl.ExampleDef{710 Target: resType,711 Name: title,712 Example: output,713 }714 i.schema.Examples = append(i.schema.Examples, ex)715 }716 }717 }718 }719 sadlName := stripNamespace(shapeName)720 if method == "" {721 odef := &sadl.OperationDef{722 Name: sadl.Uncapitalize(sadlName),723 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),724 Annotations: i.importTraitsAsAnnotations(nil, shape.Traits),725 }726 if shape.Input != nil {727 inStruct := i.ast.GetShape(inShapeName)728 var inputs []*sadl.OperationInput729 for _, fname := range inStruct.Members.Keys() {730 fval := inStruct.Members.Get(fname)731 in := &sadl.OperationInput{}732 in.Name = fname733 in.Type = i.shapeRefToTypeRef(fval.Target)734 in.Required = fval.Traits.GetBool("smithy.api#required")735 inputs = append(inputs, in)736 }737 odef.Inputs = inputs738 }739 if shape.Output != nil {740 outStruct := i.ast.GetShape(outShapeName)741 var outputs []*sadl.OperationOutput742 for _, fname := range outStruct.Members.Keys() {743 out := &sadl.OperationOutput{}744 fval := outStruct.Members.Get(fname)745 out.Name = fname746 out.Type = i.shapeRefToTypeRef(fval.Target)747 outputs = append(outputs, out)748 }749 odef.Outputs = outputs750 }751 if shape.Errors != nil {752 //fix me753 for _, err := range shape.Errors {754 odef.Exceptions = append(odef.Exceptions, i.shapeRefToTypeRef(err.Target))755 }756 }757 i.schema.Operations = append(i.schema.Operations, odef)758 //the req/resp types are getting dropped759 return760 }761 hdef := &sadl.HttpDef{762 Method: method,763 Path: uri,764 Name: sadl.Uncapitalize(sadlName),765 Comment: escapeComment(shape.Traits.GetString("smithy.api#documentation")),766 Annotations: i.importTraitsAsAnnotations(nil, shape.Traits),767 }768 if code == 0 {769 code = 200770 }771 if shape.Input != nil {772 inStruct := i.ast.GetShape(inShapeName)773 qs := ""774 payloadMember := ""775 hasLabel := false776 hasQuery := false777 if inStruct != nil {778 for _, fname := range inStruct.Members.Keys() {779 fval := inStruct.Members.Get(fname)780 if fval.Traits.GetBool("smithy.api#httpPayload") {781 payloadMember = fname782 } else if fval.Traits.GetBool("smithy.api#httpLabel") {783 hasLabel = true784 } else if fval.Traits.GetBool("smithy.api#httpQuery") {785 hasQuery = true786 }787 }788 if hasLabel || hasQuery || payloadMember != "" {789 //the input might *have* a body790 for _, fname := range inStruct.Members.Keys() {791 fval := inStruct.Members.Get(fname)792 in := &sadl.HttpParamSpec{}793 in.Name = fname794 in.Type = i.shapeRefToTypeRef(fval.Target)795 in.Required = fval.Traits.GetBool("smithy.api#required")796 in.Query = fval.Traits.GetString("smithy.api#httpQuery")797 if in.Query != "" {798 if qs == "" {799 qs = "?"800 } else {801 qs = qs + "&"802 }803 qs = qs + fname + "={" + fname + "}"804 }805 in.Header = fval.Traits.GetString("smithy.api#httpHeader")806 in.Path = fval.Traits.GetBool("smithy.api#httpLabel")807 hdef.Inputs = append(hdef.Inputs, in)808 }809 } else {810 //the input *is* a body. Generate a name for it.811 in := &sadl.HttpParamSpec{}812 in.Name = "body"813 in.Type = inType814 hdef.Inputs = append(hdef.Inputs, in)815 }816 hdef.Path = hdef.Path + qs817 }818 } else {819 // fmt.Println("no input:", data.Pretty(shape))820 }821 expected := &sadl.HttpExpectedSpec{822 Status: int32(code),823 }824 if shape.Output != nil {825 outStruct := i.ast.GetShape(outShapeName)826 //SADL: each output is a header or a (singular) payload.827 //Smithy: the output struct is the result payload, unless a field is marked as payload, which allows other fields828 //to be marked as header.829 outBodyField := ""830 hasLabel := false831 for _, fname := range outStruct.Members.Keys() {832 fval := outStruct.Members.Get(fname)833 if fval.Traits.GetBool("smithy.api#httpPayload") {834 outBodyField = fname835 } else if fval.Traits.GetBool("smithy.api#httpLabel") {836 hasLabel = true837 }838 }839 if outBodyField == "" && !hasLabel {840 //the entire output structure is the payload, no headers possible841 out := &sadl.HttpParamSpec{}842 out.Name = "body"843 out.Type = i.shapeRefToTypeRef(outType)844 expected.Outputs = append(expected.Outputs, out)845 } else {846 for _, fname := range outStruct.Members.Keys() {847 fval := outStruct.Members.Get(fname)848 out := &sadl.HttpParamSpec{}849 out.Name = fname850 out.Type = i.shapeRefToTypeRef(fval.Target)851 out.Required = fval.Traits.GetBool("smithy.api#required")852 out.Header = fval.Traits.GetString("smithy.api#httpHeader")853 out.Query = fval.Traits.GetString("smithy.api#httpQuery")854 out.Path = fval.Traits.GetBool("smithy.api#httpLabel")855 expected.Outputs = append(expected.Outputs, out)856 }857 }858 }859 if shape.Errors != nil {860 for _, etype := range shape.Errors {861 eShapeName := etype.Target862 eStruct := i.ast.GetShape(eShapeName)863 eType := i.shapeRefToTypeRef(eShapeName)864 if eStruct == nil {865 panic("error type not found: " + eShapeName)866 }867 exc := &sadl.HttpExceptionSpec{}868 exc.Type = eType869 exc.Status = int32(eStruct.Traits.GetInt("smithy.api#httpError"))870 exc.Comment = escapeComment(eStruct.Traits.GetString("smithy.api#documentation"))871 //preserve other traits as annotations?872 hdef.Exceptions = append(hdef.Exceptions, exc)873 }874 }875 //Comment string876 //Annotations map[string]string877 hdef.Expected = expected878 i.schema.Http = append(i.schema.Http, hdef)879}880func WithAnnotation(annos map[string]string, key string, value string) map[string]string {881 if value != "" {882 if annos == nil {883 annos = make(map[string]string, 0)884 }885 annos[key] = value886 }887 return annos888}889func stripNamespace(trait string) string {890 n := strings.Index(trait, "#")891 if n < 0 {892 return trait893 }894 return trait[n+1:]895}896func AssembleModel(paths []string, tags []string) (*smithylib.AST, error) {897 flatPathList, err := expandPaths(paths)898 if err != nil {899 return nil, err900 }901 assembly := &smithylib.AST{902 Smithy: "2",903 }904 for _, path := range flatPathList {905 var ast *smithylib.AST906 var err error907 ext := filepath.Ext(path)908 switch ext {909 case ".json":910 ast, err = smithylib.LoadAST(path)911 case ".smithy":912 ast, err = smithylib.Parse(path)913 default:914 return nil, fmt.Errorf("parse for file type %q not implemented", ext)915 }916 if err != nil {917 return nil, err918 }919 err = assembly.Merge(ast)920 if err != nil {921 return nil, err922 }923 }924 if len(tags) > 0 {925 assembly.Filter(tags)926 }927 err = assembly.Validate()928 if err != nil {929 return nil, err930 }931 return assembly, nil932}933var ImportFileExtensions = map[string][]string{934 ".smithy": []string{"smithy"},935 ".json": []string{"smithy"},936}937func expandPaths(paths []string) ([]string, error) {938 var result []string939 for _, path := range paths {940 ext := filepath.Ext(path)941 if _, ok := ImportFileExtensions[ext]; ok {942 result = append(result, path)943 } else {944 fi, err := os.Stat(path)945 if err != nil {946 return nil, err947 }948 if fi.IsDir() {949 err = filepath.Walk(path, func(wpath string, info os.FileInfo, errIncoming error) error {950 if errIncoming != nil {951 return errIncoming952 }953 ext := filepath.Ext(wpath)954 if _, ok := ImportFileExtensions[ext]; ok {955 result = append(result, wpath)956 }957 return nil958 })959 }960 }961 }962 return result, nil963}...
template_index.go
Source:template_index.go
1package main2const templateIndex = `3<html>4<head>5<meta charset="utf-8">6<title>{{.Cfg.GetString "name" "Unnamed"}}</title>7<link href="http://netdna.bootstrapcdn.com/bootswatch/3.0.2/spacelab/bootstrap.min.css" rel="stylesheet">8<head>9<body>10<div class="container">11 <div class="page-header">12 <h1>Experiment report: {{.Cfg.GetString "name" "Unnamed"}}</h1>13 </div>14 <div class="panel panel-default">15 <div class="panel-heading">16 <h3 class="panel-title">General</h3>17 </div>18 <div class="panel-body">19 <ul>20 <li>Date: {{.Timestamp}}</li>21 <li>Duration: {{.Cfg.GetString "duration" "N/A"}}</li>22 <li>Runs: {{.Cfg.GetInt "runs" 0}}</li>23 <li>Remote user: {{.Cfg.GetString "remoteUser" "N/A"}}</li>24 <li>Remote scratch dir: {{.Cfg.GetString "remoteScratchDir" ""}}</li>25 </ul>26 </div>27 </div>28 <div class="panel panel-default">29 <div class="panel-heading">30 <h3 class="panel-title">Versions</h3>31 </div>32 <div class="panel-body">33 <ul>34 <li>{{.Go}}</li>35 <li>goxos: {{.Goxos}}</li>36 </ul>37 </div>38 </div>39 <div class="panel panel-default">40 <div class="panel-heading">41 <h3 class="panel-title">Cluster</h3>42 </div>43 <div class="panel-body">44 <p>Replicas:</p>45 <ul>46 {{range .Hostnames.Nodes}}47 <li>{{.}}</li>48 {{else}} 49 <li>None found</li>50 {{end}} 51 </ul>52 <p>Standbys:</p>53 <ul>54 {{range .Hostnames.Standbys}}55 <li>{{.}}</li>56 {{else}} 57 <li>None found</li>58 {{end}} 59 </ul>60 <p>Clients:</p>61 <ul>62 {{range .Hostnames.Clients}}63 <li>{{.}}</li>64 {{else}} 65 <li>None found</li>66 {{end}} 67 </ul>68 </div>69 </div>70 <div class="panel panel-default">71 <div class="panel-heading">72 <h3 class="panel-title">Failures</h3>73 </div>74 <div class="panel-body">75 {{if .Hostnames.Failures}}76<!-- <ul>77 {{range .Hostnames.Failures}}78 <li>{{.}} (+{{/* .Time */}} seconds)</li>79 {{end}}80 </ul> -->81 <ul>{{.Cfg.GetString "failures" ""}}</ul>82 {{else}}83 <p>No failures defined for this experiment.</p>84 {{end}}85 </div>86 </div>87 <div class="panel panel-default">88 <div class="panel-heading">89 <h3 class="panel-title">State</h3>90 </div>91 <div class="panel-body">92 <ul>93 {{if (.Cfg.GetString "replicaInitialState" "")}}94 <li>Initial replica state: {{.Cfg.GetString "replicaInitialState" ""}}</li>95 {{else}}96 <li>Initial replica state: None</li> 97 {{end}}98 </ul>99 </div>100 </div>101 <div class="panel panel-default">102 <div class="panel-heading">103 <h3 class="panel-title">Paxos Settings</h3>104 </div>105 <div class="panel-body">106 <ul>107 <li>Paxos type: {{.Cfg.GetString "protocol" ""}}</li>108 <li>Alpha: {{.Cfg.GetInt "alpha" 0}}</li>109 <li>BatchMaxSize: {{.Cfg.GetInt "batchMaxSize" 0}}</li>110 <li>BatchTimeout: {{.Cfg.GetString "batchTimeout" "N/A"}}</li>111 <li>Failure handling type: {{.Cfg.GetString "failureHandlingType" ""}}</li>112 </ul>113 </div>114 </div>115 <div class="panel panel-default">116 <div class="panel-heading">117 <h3 class="panel-title">Liveness Settings</h3>118 </div>119 <div class="panel-body">120 <ul>121 <li>Heartbeat emitter interval: {{.Cfg.GetString "hbEmitterInterval" "N/A"}}</li>122 <li>Failure detector timeout interval: {{.Cfg.GetString "fdTimeoutInterval" "N/A"}}</li>123 <li>Failure detector delta increase: {{.Cfg.GetString "fdDeltaIncrease" "N/A"}}</li>124 </ul>125 </div>126 </div>127 <div class="panel panel-default">128 <div class="panel-heading">129 <h3 class="panel-title">Client Settings</h3>130 </div>131 <div class="panel-body">132 <ul>133 <li>Clients per machine: {{.Cfg.GetString "clientsPerMachine" "N/A"}}</li>134 <li>Number of runs: {{.Cfg.GetString "clientsNumberOfRuns" "N/A"}}</li>135 <li>Number of commands: {{.Cfg.GetString "clientsNumberOfCommands" "N/A"}}</li>136 <li>Key size: {{.Cfg.GetString "clientsKeySize" "N/A"}} bytes</li>137 <li>Value size: {{.Cfg.GetString "clientsValueSize" "N/A"}} bytes</li>138 </ul>139 </div>140 </div>141 {{if .LREnabled}}142 <div class="panel panel-default">143 <div class="panel-heading">144 <h3 class="panel-title">Live Replacement Settings</h3>145 </div>146 <div class="panel-body">147 <ul>148 {{if (.Cfg.GetString "LRExpRndSleep" "")}}149 <li>Random pre-connecy sleep enabled: {{.Cfg.GetString "LRExpRndSleep" ""}} ms</li>150 {{else}}151 <li>Random pre-connect sleep not enabled</li>152 {{end}}153 <li>Strategy: {{.Cfg.GetString "LRStrategy" "N/A"}}</li>154 </ul>155 </div>156 </div>157 {{end}}158 <div class="panel panel-default">159 <div class="panel-heading">160 <h3 class="panel-title">Logging</h3>161 </div>162 <div class="panel-body">163 <ul>164 <li>glog v-level: {{.Cfg.GetString "glogVLevel" "N/A"}}</li>165 {{if (.Cfg.GetString "glogVModule" "")}}166 <li>glog vmodule argument: {{.Cfg.GetString "glogVModule" "N/A"}}</li>167 {{end}}168 <li>Throughput sampling interval: {{.Cfg.GetString "throughputSamplingInterval" "N/A"}}</li>169 </ul>170 </div>171 </div>172 <div class="panel panel-default">173 <div class="panel-heading">174 <h3 class="panel-title">Experiment Runs ({{.ValidRuns}} of {{.Cfg.GetString "runs" "0"}} valid)</h3>175 </div>176 <div class="panel-body">177 <div class="list-group">178 {{range .ExpRuns}}179 <a href="{{.ID}}/{{.ID}}.html" class="list-group-item">180 {{if .Valid}}181 <h4 class="list-group-item-heading">182 Run {{.ID}}183 <span class="label label-success">Valid</span>184 </h4>185 {{else}}186 <h4 class="list-group-item-heading">187 Run {{.ID}}188 <span class="label label-danger">Invalid</span>189 </h4>190 {{end}}191 </a>192 {{else}}193 <a href="#" class="list-group-item">194 <h4 class="list-group-item-heading">No runs found...</h4>195 </a>196 {{end}}197 </div>198 </div>199 </div>200 <div class="panel panel-default">201 <div class="panel-heading">202 <h3 class="panel-title">Durations</h3>203 </div>204 <div class="panel-body">205 {{if .Analysed}}206 <table class="table">207 <thead>208 <tr>209 <th>Failure handling interval</th>210 <th>Duration</th>211 </tr>212 </thead>213 <tbody>214 <tr class="success">215 <td>216 Initialization (mean):217 </td>218 <td>219 {{.InitDurMean}}220 </td>221 </tr>222 <tr>223 <td>224 Initialization (standard deviation):225 </td>226 <td>227 {{.InitDurSD}}228 </td>229 </tr>230 <tr>231 <td>232 Initialization (standard error of mean):233 </td>234 <td>235 {{.InitDurSdOfMean}}236 </td>237 </tr>238 <tr>239 <td>240 Initialization (min):241 </td>242 <td>243 {{.InitDurMin}}244 </td>245 </tr>246 <tr>247 <td>248 Initialization (max):249 </td>250 <td>251 {{.InitDurMax}}252 </td>253 </tr>254 <tr class="success">255 <td>256 Activation (mean):257 </td>258 <td>259 {{.ActiDurMean}}260 </td>261 </tr>262 <tr>263 <td>264 Activation (standard deviation):265 </td>266 <td>267 {{.ActiDurSD}}268 </td>269 </tr>270 <tr>271 <td>272 Activation (standard error of mean):273 </td>274 <td>275 {{.ActiDurSdOfMean}}276 </td>277 </tr>278 <tr>279 <td>280 Activation (min):281 </td>282 <td>283 {{.ActiDurMin}}284 </td>285 </tr>286 <tr>287 <td>288 Activation (max):289 </td>290 <td>291 {{.ActiDurMax}}292 </td>293 </tr>294 <tr class="success">295 <td>296 Wait for Acc (mean):297 </td>298 <td>299 {{.FAccDurMean}}300 </td>301 </tr>302 <tr>303 <td>304 First Acc (standard deviation):305 </td>306 <td>307 {{.FAccDurSD}}308 </td>309 </tr>310 <tr>311 <td>312 First Acc (standard error of mean):313 </td>314 <td>315 {{.FAccDurSdOfMean}}316 </td>317 </tr>318 <tr>319 <td>320 First Acc (min):321 </td>322 <td>323 {{.FAccDurMin}}324 </td>325 </tr>326 <tr>327 <td>328 First Acc (max):329 </td>330 <td>331 {{.FAccDurMax}}332 </td>333 </tr>334 {{if .ARecEnabled}}335 <tr class="success">336 <td>337 Activated from CPromises (mean):338 </td>339 <td>340 {{.ARecActiDurMean}}341 </td>342 </tr>343 <tr>344 <td>345 Activated from CPromises (standard deviation):346 </td>347 <td>348 {{.ARecActiDurSD}}349 </td>350 </tr>351 <tr>352 <td>353 Activated from CPromises (standard error of mean):354 </td>355 <td>356 {{.ARecActiDurSdOfMean}}357 </td>358 </tr>359 <tr>360 <td>361 Activated from CPromises (min):362 </td>363 <td>364 {{.ARecActiDurMin}}365 </td>366 </tr>367 <tr>368 <td>369 Activated from CPromises (max):370 </td>371 <td>372 {{.ARecActiDurMax}}373 </td>374 </tr>375 {{end}}376 </tbody>377 </table>378 {{else}}379 <div class="alert alert-danger">{{.Comment}}</div>380 {{end}}381 </div>382 </div>383 <div class="panel panel-default">384 <div class="panel-heading">385 <h3 class="panel-title">Throughput</h3>386 </div>387 <div class="panel-body">388 <table class="table">389 <thead>390 <tr>391 <th>Average throughput</th>392 <th>Paxos leader throughput (req/sec)</th>393 </tr>394 </thead>395 <tbody>396 <tr>397 <td>398 Total average throughput:399 </td>400 <td>401 {{.TotalAverageThroughput}}402 </td>403 </tr>404 </tbody>405 </table>406 </div>407 <div class="panel-body">408 {{if .Analysed}}409 <table class="table">410 <thead>411 <tr>412 <th>Failure handling interval</th>413 <th>Paxos leader throughput (req/sec)</th>414 </tr>415 </thead>416 <tbody>417 <tr class="success">418 <td>419 Baseline (mean):420 </td>421 <td>422 {{.BaseTputMean}}423 </td>424 </tr>425 <tr>426 <td>427 Baseline (standard deviation):428 </td>429 <td>430 {{.BaseTputSSD}}431 </td>432 </tr>433 <tr>434 <td>435 Baseline (standard error of mean):436 </td>437 <td>438 {{.BaseTputStdErrOfMean}}439 </td>440 </tr>441 <tr>442 <td>443 Baseline (min):444 </td>445 <td>446 {{.BaseTputMin}}447 </td>448 </tr>449 <tr>450 <td>451 Baseline (max):452 </td>453 <td>454 {{.BaseTputMax}}455 </td>456 </tr>457 <tr class="success">458 <td>459 Initialization (mean):460 </td>461 <td>462 {{.InitTputMean}}463 </td>464 </tr>465 <tr>466 <td>467 Initialization (standard deviation):468 </td>469 <td>470 {{.InitTputSSD}}471 </td>472 </tr>473 <tr>474 <td>475 Initialization (standard error of mean):476 </td>477 <td>478 {{.InitTputStdErrOfMean}}479 </td>480 </tr>481 <tr>482 <td>483 Initialization (min):484 </td>485 <td>486 {{.InitTputMin}}487 </td>488 </tr>489 <tr>490 <td>491 Initialization (max):492 </td>493 <td>494 {{.InitTputMax}}495 </td>496 </tr>497 <tr class="success">498 <td>499 Activation (mean):500 </td>501 <td>502 {{.ActiTputMean}}503 </td>504 </tr>505 <tr>506 <td>507 Activation (standard deviation):508 </td>509 <td>510 {{.ActiTputSSD}}511 </td>512 </tr>513 <tr>514 <td>515 Activation (standard error of mean):516 </td>517 <td>518 {{.ActiTputStdErrOfMean}}519 </td>520 </tr>521 <tr>522 <td>523 Activation (min):524 </td>525 <td>526 {{.ActiTputMin}}527 </td>528 </tr>529 <tr>530 <td>531 Activation (max):532 </td>533 <td>534 {{.ActiTputMax}}535 </td>536 </tr>537 </tbody>538 </table>539 {{else}}540 <div class="alert alert-danger">{{.Comment}}</div>541 {{end}}542 </div>543 </div>544 <div class="panel panel-default">545 <div class="panel-heading">546 <h3 class="panel-title">Latencies</h3>547 </div>548 <div class="panel-body">549 {{if .Analysed}}550 <table class="table">551 <thead>552 <tr>553 <th>Latencies</th>554 <th>in ms</th>555 </tr>556 </thead>557 <tbody>558 <tr class="success">559 <td>560 Median Latency :561 </td>562 <td>563 {{.MeanLatency}}564 </td>565 </tr>566 <tr>567 <td>568 Median 90% Low Error:569 </td>570 <td>571 {{.MeanLatMin90}}572 </td>573 </tr>574 <tr>575 <td>576 Median 90% High Error:577 </td>578 <td>579 {{.MeanLatMax90}}580 </td>581 </tr>582 <tr>583 <td>584 Spike Latency (Median):585 </td>586 <td>587 {{.MeanMaxLatency}}588 </td>589 </tr>590 <tr>591 <td>592 Activation Latency (Median):593 </td>594 <td>595 {{.MeanMaxActLatency}}596 </td>597 </tr>598 <tr>599 <td>600 Activation Latency Low 90% Error:601 </td>602 <td>603 {{.MMALMin90}}604 </td>605 </tr>606 <tr>607 <td>608 Activation Latency High 90% Error:609 </td>610 <td>611 {{.MMALMax90}}612 </td>613 </tr>614 </tbody>615 </table>616 {{else}}617 <div class="alert alert-danger">{{.Comment}}</div>618 {{end}}619 </div>620 </div>621</div>622</body>623</html>`...
admin.go
Source:admin.go
1package controllers2import (3 "ftpd/models"4 "os"5 "path/filepath"6 "strconv"7 "strings"8 "ftpd/conf"9 "github.com/astaxie/beego"10 "encoding/json"11)12//跳转Controller13type AdminController struct {14 beego.Controller15}16//跳转Controller17type AdminUserController struct {18 beego.Controller19}20type AdminUserCheckPathController struct {21 beego.Controller22}23type AdminUserDeleteController struct {24 beego.Controller25}26type AdminUserGetInfoController struct {27 beego.Controller28}29type AdminUserEditController struct {30 beego.Controller31}32type AdminSysController struct {33 beego.Controller34}35type AdminSysGetController struct {36 beego.Controller37}38type AdminSysSetController struct {39 beego.Controller40}41//å¤ææ¯å¦å·²ç»é并跳转42func (c *AdminController) Get() {43 if CheckLogin(&c.Controller, 2) == false {44 c.StopRun()45 }46 c.Redirect("/admin/user", 302)47}48func (c *AdminSysController) Get() {49 if CheckLogin(&c.Controller, 2) == false {50 c.StopRun()51 }52 c.Data["IsSys"] = true53 c.TplName = "admin.tpl"54}55func (c *AdminSysGetController) Get() {56 if CheckLogin(&c.Controller, 2) == false {57 c.StopRun()58 }59 b,_:=models.GetAllSetting()60 c.Ctx.ResponseWriter.Write(b)61 c.Ctx.ResponseWriter.WriteHeader(200)62}63func (c *AdminSysSetController) Post() {64 if CheckLogin(&c.Controller, 2) == false {65 c.StopRun()66 }67 data:=c.GetString("d")68 var tmp []models.Config69 if err:=json.Unmarshal([]byte(data),&tmp);err!=nil{70 c.StopRun()71 }72 //TODO73 if len(tmp)>0 {74 if err:=models.SetSetting(tmp[0].Name,tmp[0].Value);err!=nil{75 println(err.Error())76 }77 }78 c.StopRun()79}80func (c *AdminUserController) Get() {81 if CheckLogin(&c.Controller, 2) == false {82 c.StopRun()83 }84 var list []models.User85 models.GetAllUser(&list)86 var tmp string87 var stat string88 var size string89 var readwritedelete string90 var totalsize int6491 for _, v := range list {92 totalsize = 093 readwritedelete = "读:x å:x å :x"94 switch v.Type {95 case 0:96 stat = "æªæ¿æ´»"97 case 1:98 stat = "æ®éç¨æ·"99 case 2:100 stat = "管çå"101 default:102 stat = "å¼å¸¸"103 }104 if v.Read {105 readwritedelete = strings.Replace(readwritedelete, "读:x", "读:â", 1)106 }107 if v.Write {108 readwritedelete = strings.Replace(readwritedelete, "å:x", "å:â", 1)109 }110 if v.Delete {111 readwritedelete = strings.Replace(readwritedelete, "å :x", "å :â", 1)112 }113 if v.Path == "" {114 size = "0KB"115 } else {116 path := conf.Ftppath+ "/" + v.Path117 _, err1 := os.Stat(path)118 if err1 == nil {119 filepath.Walk(path, func(f string, info os.FileInfo, err error) error {120 totalsize += info.Size()121 return err122 })123 size = strconv.FormatInt(totalsize/1024, 10) + "KB"124 } else {125 size = "ç®å½æå"126 }127 }128 tmp += `<tr>129 <td>` + strconv.Itoa(v.Id) + `</td>130 <td>` + v.Username + `</td>131 <td>` + stat + `</td>132 <td>` + size + `</td>133 <td>` + readwritedelete + `</td>134 <td><btn class="btn btn-info" data-toggle="modal" data-target="#editModal" onclick="edituserconfirm(this)">ä¿®æ¹</button></td>135 <td><btn class="btn btn-danger" data-toggle="modal" data-target="#delModal" onclick="deleteuserconfirm(this)">å é¤</button></td>136 </tr>`137 }138 c.Data["UserList"] = beego.Str2html(tmp)139 c.Data["IsUser"] = true140 c.TplName = "admin.tpl"141}142func (c *AdminUserCheckPathController) Post() {143 if CheckLogin(&c.Controller, 2) == false {144 c.StopRun()145 }146 id := c.GetString("id")147 if id == "" {148 c.StopRun()149 }150 idn, _ := strconv.Atoi(id)151 msg := models.GetPathUser(idn)152 if msg == "" {153 c.Ctx.WriteString("å é¤åæ¤ç¨æ·çæ件ç®å½ä¹åæ¶å é¤æä¸æ æ³æ¢å¤ï¼" + msg)154 c.StopRun()155 }156 c.Ctx.WriteString("æ¤ç¨æ·ä¸ä¸åç¨æ·å
±ç¨åä¸ç®å½ï¼æ¤æ¬¡å é¤ä¸ä¼å é¤ææ件ç®å½ï¼é¤éä½ æä¸åææç¨æ·é½å é¤ï¼<br/>" + msg)157 c.StopRun()158}159func (c *AdminUserDeleteController) Post() {160 if CheckLogin(&c.Controller, 2) == false {161 c.StopRun()162 }163 id := c.GetString("id")164 if id == "" || id == "1" {165 c.Ctx.WriteString("æä½å¤±è´¥ï¼")166 c.StopRun()167 }168 idn, _ := strconv.Atoi(id)169 tmp, err1 := models.GetUserInfo(idn)170 if err1 != nil {171 c.Ctx.WriteString("æä½å¤±è´¥ï¼")172 c.StopRun()173 }174 msg := models.GetPathUser(idn)175 if msg == "" && tmp.Path != "" {176 os.RemoveAll(conf.Ftppath + "/" + tmp.Path)177 }178 models.DeleteUser(tmp)179 c.Ctx.WriteString("æä½æåï¼")180 c.StopRun()181}182func (c *AdminUserGetInfoController) Post() {183 if CheckLogin(&c.Controller, 2) == false {184 c.StopRun()185 }186 id := c.GetString("id")187 idn, _ := strconv.Atoi(id)188 tmp, err := models.GetUserInfo(idn)189 if err != nil {190 c.Ctx.WriteString("æä½å¤±è´¥ï¼")191 c.StopRun()192 }193 msg := "|r|w|d"194 if tmp.Read {195 msg = strings.Replace(msg, "r", "1", 1)196 } else {197 msg = strings.Replace(msg, "r", "0", 1)198 }199 if tmp.Write {200 msg = strings.Replace(msg, "w", "1", 1)201 } else {202 msg = strings.Replace(msg, "w", "0", 1)203 }204 if tmp.Delete {205 msg = strings.Replace(msg, "d", "1", 1)206 } else {207 msg = strings.Replace(msg, "d", "0", 1)208 }209 msg = strconv.Itoa(tmp.Type) + "|" + tmp.Path + msg210 c.Ctx.WriteString(msg)211}212func (c *AdminUserEditController) Post() {213 ret := "<script>alert('msg');location.href='/admin/user';</script>"214 if CheckLogin(&c.Controller, 2) == false {215 c.Ctx.WriteString(strings.Replace(ret, "msg", "æä½å¤±è´¥ï¼æéä¸è¶³", -1))216 c.StopRun()217 }218 id, usertype, password, path, canread, canwrite, candelete := c.GetString("id"), c.GetString("usertype"), c.GetString("password"), c.GetString("path"), c.GetString("read"), c.GetString("write"), c.GetString("delete")219 if id == "" || usertype == "" {220 c.Ctx.WriteString(strings.Replace(ret, "msg", "æä½å¤±è´¥ï¼åæ°ä¸å®æ´", -1))221 c.StopRun()222 }223 idn, _ := strconv.Atoi(id)224 tmp, err := models.GetUserInfo(idn)225 if err != nil {226 c.Ctx.WriteString(strings.Replace(ret, "msg", "æä½å¤±è´¥ï¼ç¨æ·ä¸åå¨", -1))227 c.StopRun()228 }229 if !models.CheckPathAvailable(path) {230 c.Ctx.WriteString(strings.Replace(ret, "msg", "æä½å¤±è´¥ï¼ç®å½ååä¸ç¬¦åå½åè§èï¼ä¸å¾å«æ..,<>,/,\\,|,:,\"\",*,?ï¼", -1))231 c.StopRun()232 }233 if idn != 1 {234 switch usertype {235 case "0":236 tmp.Type = 0237 case "1":238 tmp.Type = 1239 case "2":240 tmp.Type = 2241 }242 }243 if password != "" {244 tmp.Password = password245 }246 if canread == "1" {247 tmp.Read = true248 } else {249 tmp.Read = false250 }251 if canwrite == "1" {252 tmp.Write = true253 } else {254 tmp.Write = false255 }256 if candelete == "1" {257 tmp.Delete = true258 } else {259 tmp.Delete = false260 }261 tmp.Path = path262 pathmsg := ""263 realpath := conf.Ftppath + path264 if _, patherr := os.Stat(realpath); patherr != nil {265 if err:=os.Mkdir(realpath, 0777);err!=nil{266 println("å建ç®å½å¤±è´¥ï¼åå ï¼",err.Error())267 }268 pathmsg = "ç³»ç»æ£æµå°æ¤ç®å½ä¸åå¨ï¼å·²ç»æåå¸®ä½ å建æ¤ç®å½ã"269 }270 models.EditUser(tmp)271 c.Ctx.WriteString(strings.Replace(ret, "msg", "æä½æåï¼"+pathmsg, -1))272}...
getString
Using AI Code Generation
1import (2func main() {3 fmt.Println(td.GetString())4}5import (6func main() {7 fmt.Println(td.GetString())8}9import (10func main() {11 fmt.Println(td.GetString())12}13import (14func main() {15 fmt.Println(td.GetString())16}
getString
Using AI Code Generation
1import (2func main() {3 fmt.Println(td.GetString())4}5import (6func main() {7 fmt.Println(td.GetString())8}9import "fmt"10type td struct {11}12func (t td) getString() string {13}14func GetString() string {15 t := td{}16 return t.getString()17}18import "fmt"19type td struct {20}21func (t td) getString() string {22}23func GetString() string {24 t := td{}25 return t.getString()26}27import "fmt"28type td struct {29}30func (t td) getString() string {31}32func GetString() string {33 t := td{}34 return t.getString()35}36import "fmt"37type td struct {38}39func (t td) getString() string {40}41func GetString() string {42 t := td{}43 return t.getString()44}45import "fmt"46type td struct {47}48func (t td) getString() string {49}50func GetString() string {51 t := td{}52 return t.getString()53}54import "fmt"55type td struct {56}57func (t td) getString() string {58}59func GetString() string {60 t := td{}61 return t.getString()62}63import "fmt"64type td struct {65}66func (t td) getString() string {67}68func GetString() string {69 t := td{}70 return t.getString()71}72import "fmt"73type td struct {74}75func (t td) getString() string
getString
Using AI Code Generation
1import (2type td struct {3}4func (t td) getString() string {5}6func main() {7 t := td{s: "Hello World"}8 fmt.Println(t.getString())9}
getString
Using AI Code Generation
1import (2func main() {3 fmt.Println(td.GetString())4}5import (6func main() {7 fmt.Println(td.GetString())8}9import (10func main() {11 fmt.Println(td.GetString())12}13import (14func main() {15 fmt.Println(td.GetString())16}17import (18func main() {19 fmt.Println(td.GetString())20}21import (22func main() {23 fmt.Println(td.GetString())24}25import (26func main() {27 fmt.Println(td.GetString())28}29import (30func main() {31 fmt.Println(td.GetString())32}33import (34func main() {35 fmt.Println(td.GetString())36}37import (38func main() {39 fmt.Println(td.GetString())40}41import (42func main() {43 fmt.Println(td.GetString())44}45import (46func main() {47 fmt.Println(td.GetString())48}49import (50func main() {
getString
Using AI Code Generation
1import (2func main() {3 fmt.Println(td.GetString())4}5import (6func main() {7 fmt.Println(td.GetString())8}9import (10func main() {11 fmt.Println(td.GetString())12}13import (14func main() {15 fmt.Println(td.GetString())16}17import (18func main() {19 fmt.Println(td.GetString())20}21import (22func main() {23 fmt.Println(td.GetString())24}25import (26func main() {27 fmt.Println(td.GetString())28}29import (30func main() {31 fmt.Println(td.GetString())32}33import (34func main() {35 fmt.Println(td.GetString())36}37import (38func main() {39 fmt.Println(td.GetString())40}41import (42func main() {43 fmt.Println(td.GetString())44}45import (46func main() {47 fmt.Println(td.GetString())48}
getString
Using AI Code Generation
1import (2func main() {3 fmt.Println(t.GetString())4}5import (6func main() {7 fmt.Println(t.GetString())8}9import (10func main() {11 fmt.Println(t.GetString())12}13import (14func main() {15 fmt.Println(t.GetString())16}17import (18func main() {19 fmt.Println(t.GetString())20}21import (22func main() {23 fmt.Println(t.GetString())24}25import (26func main() {27 fmt.Println(t.GetString())28}29import (30func main() {31 fmt.Println(t.GetString())32}33import (34func main() {35 fmt.Println(t.GetString())36}37import (38func main() {39 fmt.Println(t.GetString())40}
getString
Using AI Code Generation
1import (2func main() {3 td := td{}4 fmt.Println(td.getString())5}6type struct_name struct {7}8import "fmt"9type employee struct {10}11func main() {12 emp1 := employee{"Alex", 30, 5000}13 emp2 := employee{"John", 25, 6000}14 emp3 := employee{"Bob", 35, 7000}15 fmt.Println("Employee 1", emp1)16 fmt.Println("Employee 2", emp2)17 fmt.Println("Employee 3", emp3)18}19Employee 1 {Alex 30 5000}20Employee 2 {John 25 6000}21Employee 3 {Bob 35 7000}22import "fmt"23type employee struct {24}25func main() {26 emp1 := employee{"Alex", 30, 5000}27 emp2 := employee{"John", 25, 6000}28 emp3 := employee{"Bob", 35, 7000}29 fmt.Println("Employee 1", emp1.name)30 fmt.Println("Employee 2", emp2.age)31 fmt.Println("Employee 3", emp3.salary)32}
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!!