I am trying to create a response like this:
"GameController" => [
"methods" => [
"get",
"post",
"put",
"delete"
],
]
Following is the script I wrote for this:
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
}
But this script is showing the following error. How can I fix this error? Please advice.
cannot use SearchMethod(filename) (type map[string][]string) as type []string in assignment go
the error is showing up in this line allcontrollers[filename] = SearchMethod(filename)
You are getting that error because of the way you are defining the var "allcontrollers". You should define it as the following:
allcontrollers := map[string](map[string][]string){}
With this, the problem will be solved.