0

我正在尝试创建这样的响应:

"GameController" => [
    "methods" => [
        "get",
        "post",
        "put",
        "delete"
    ],
]

以下是我为此编写的脚本:

main.go

package main

import (
    "fmt"
    "openapi/parse"
)

func main() {

    controllers := []string{"GameController", "CardController", "ShuffleController"}

    fmt.Println(parse.GetHTTPMethods(controllers))
}

get_http_methods.go

package parse

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

    // GetHTTPMethods will return the available http methods of each controller
    func GetHTTPMethods(controllers []string) map[string][]string {
        allcontrollers := map[string][]string{}
        for _, filename := range controllers {
            allcontrollers[filename] = SearchMethod(filename)
        }
        
        return allcontrollers
    }
    //SearchMethod will read each controller and search for available http methods
    func SearchMethod(filename string) map[string][]string {
        path := "../hbapi/application/controllers/" + filename + ".php"
        method := map[string][]string{}
        f, err := os.Open(path)
        if err != nil {
            fmt.Println("Error : ", err)
            os.Exit(1)
        }
        defer f.Close()
        scanner := bufio.NewScanner(f)
        for scanner.Scan() {
            if strings.Contains(scanner.Text(), "Get") {
                method["method"] = append(method["method"], "get")
            }
            if strings.Contains(scanner.Text(), "Post") {
                method["method"] = append(method["method"], "post")
            }
            if strings.Contains(scanner.Text(), "Put") {
                method["method"] = append(method["method"], "put")
            }
            if strings.Contains(scanner.Text(), "Delete") {
                method["method"] = append(method["method"], "delete")
            }
        }
        if err := scanner.Err(); err != nil {
            fmt.Println("Error : ", err)
            os.Exit(1)
        }
        return method
    }

但是此脚本显示以下错误。我该如何解决这个错误?请指教。

不能使用 SearchMethod(filename) (type map[string][]string) 作为 type []string in assignment go

错误出现在这一行 allcontrollers[filename] = SearchMethod(filename)

4

1 回答 1

2

由于您定义 var“allcontrollers”的方式,您会收到该错误。您应该将其定义如下:

allcontrollers := map[string](map[string][]string){}

这样,问题就迎刃而解了。

于 2021-02-08T15:40:18.777 回答