7

I am attempting to create a sort of function that is similar to the Express (NodeJS) route method in Go:

app.get("route/here/", func(req, res){
    res.DoStuff()
});    

In this example I want "foo" (the type) to be the same as the anonymous function in the above method. Here is one of my failed attempts using Go:

type foo func(string, string)

func bar(route string, io foo) {
        log.Printf("I am inside of bar")
        // run io, maybe io() or io(param, param)?
}

func main() {
        bar("Hello", func(arg1, arg2) {
                return  arg + arg2
        })
}

How might I fix my dilemma? Should I not use a type and use something else? What are my options?

2
  • Side note but probably related - In terms of cool Go web frameworks that use a middleware pattern with a general syntax that might be familiar to Express is echo.labstack.com. Commented Oct 4, 2016 at 2:14
  • @syllabix I am trying to create a copy of Echo :) Commented Oct 4, 2016 at 2:16

2 Answers 2

15

You are on the right track - creating a type for a func in the context you are using it adds clearer design intent and additional type safety.

You just need to modify your example a bit for it to compile:

package main

import "log"

//the return type of the func is part of its overall type definition - specify string as it's return type to comply with example you have above
type foo func(string, string) string

func bar(route string, io foo) {

    log.Printf("I am inside of bar")
    response := io("param", "param")
    log.Println(response)

}

func main() {

    bar("Hello", func(arg1, arg2 string) string {
        return arg1 + arg2
    })

}
Sign up to request clarification or add additional context in comments.

Comments

1
package main

import (
    "fmt"
    "log"
)

type foo func(string, string)

func bar(route string, callback foo) bool {
 //...logic

  /* you can return the callback to use the 
     parameters and also in the same way you 
     could verify the bar function
   */
    callback("param", "param")
    return true
}

func main() {
    fmt.Println("Hello, playground")

    res := bar("Hello", func(arg1, arg2 string) {
        log.Println(arg1 + "_1")
        log.Println(arg2 + "_2")
    })

    fmt.Println("bar func res: ", res)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.