Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

httprouter.go Need Type Assertion #292

Closed
Linuturk opened this issue Oct 12, 2017 · 19 comments
Closed

httprouter.go Need Type Assertion #292

Linuturk opened this issue Oct 12, 2017 · 19 comments
Labels

Comments

@Linuturk
Copy link

Hey guys,

Not sure why I'm getting this error when I attempt to build with api2go:

github.com/manyminds/api2go/routing/httprouter.go:51: cannot use notAllowedHandler (type http.Handler) as type http.HandlerFunc in assignment: need type assertion

Seems to be this line here: https://github.com/manyminds/api2go/blob/master/routing/httprouter.go#L51

If I comment this out everything seems to validate fine. Given the code in that section is from two years ago, I imagine there's just a small tweak that needs to be made?

@sharpner
Copy link
Member

Can you show us how you are using it? A bit of code might help to find the problem.

@sharpner
Copy link
Member

sharpner commented Oct 13, 2017

Tried to dig into this blindly, but I can't reproduce any error:

package main
import (
        "fmt"
        "net/http"
        "github.com/manyminds/api2go"
        "github.com/manyminds/api2go/routing"
)
func test() http.Handler {
        return nil
}
func main() {
        routing.NewHTTPRouter("a", test())
        test := api2go.NewAPIWithBaseURL("/", "/")
        fmt.Printf("%'v", test)
}

works as expected. Maybe you are having an outdated version of httprouter or any other dependency.. possibly try updating them first and then we can search further :)

@Linuturk
Copy link
Author

Linuturk commented Oct 13, 2017

Yeah, sorry for the lack of context.

$ go version
go version go1.9.1 linux/amd64

Here are the related sections of dep status, just updated yesterday before submitting the issue.

github.com/gorilla/context           *              v1.1           1ea2538   1ea2538  1  
github.com/gorilla/handlers          ^1.2.1         v1.2.1         a4043c6   a4043c6  1  
github.com/gorilla/mux               ^1.4.0         v1.5.0         24fca30   24fca30  1
github.com/manyminds/api2go          *              0.6            02704db   02704db  3 
github.com/manyminds/api2go-adapter  *              branch master  13346ba   13346ba  1

Was trying to figure out how to integrate into my existing code base that uses gorilla mux. I found this Example and tried to go down this route: https://github.com/manyminds/api2go-adapter/tree/master/gorillamux

	r := mux.NewRouter()
	api := api2go.NewAPIWithRouting(
		"api",
		api2go.NewStaticResolver("/"),
		api2go.DefaultContentMarshalers,
		gorillamux.New(r),
	)
... r.HandleFunc routes here ...
... LIstenAndServe...

Results in the error I initially reported.

@Linuturk
Copy link
Author

Related to manyminds/api2go-adapter#5 it seems.

@sharpner
Copy link
Member

so it is fixed for you?

@Linuturk
Copy link
Author

No, when I have the above code snippet as provided in the gorillamux adapter example, I get the error in the initial report.

@sharpner
Copy link
Member

ah sry I overlooked that one comment :)

@sharpner
Copy link
Member

sharpner commented Oct 13, 2017

Ah I see now you are using an old version of api2go from november 2015..... puh it's hard to provide any help here, but I would guess that the adapter version would be too new...

@Linuturk
Copy link
Author

Is this the recommended way to connect api2go to gorilla mux, or would you recommend a different method?

@sharpner
Copy link
Member

Currently that's the way to do it, I just tested it:

package main
import (
        "net/http"
        "github.com/gorilla/mux"
        "github.com/manyminds/api2go"
        "github.com/manyminds/api2go-adapter/gorillamux"
)
func main() {
        r := mux.NewRouter()
        api := api2go.NewAPIWithRouting(
                "api",
                api2go.NewStaticResolver("/"),
                gorillamux.New(r),
        )
        // Add your API resources here...
        // see https://github.com/manyminds/api2go for more information
        r.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
                w.WriteHeader(http.StatusOK)
                w.Write([]byte("pong"))
        }).Methods("GET")
        http.Handle("/api", api.Handler())
        http.Handle("/", r)
        http.ListenAndServe(":2020", nil)
}

this will work with all versions on master. On version 0.6 somethings might be a lot different. But I understand the confusion, the Readme.md in the adapter package is outdated... We will improve and update all documentation. That should not happen - sorry :/

@Linuturk
Copy link
Author

Linuturk commented Oct 13, 2017

Here's a larger snippet of my code:

package mypackage

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
	"github.com/manyminds/api2go"
	"github.com/manyminds/api2go-adapter/gorillamux"
)

// Handler creates and returns a logging handler
func Handler() http.Handler {
	// new mux
	r := mux.NewRouter()
	api := api2go.NewAPIWithRouting(
		"api",
		api2go.NewStaticResolver("/"),
		gorillamux.New(r),
	)

	// Index, Healthcheck
	r.HandleFunc("/", Index)
	r.HandleFunc("/healthcheck", HealthCheck)

... snip a bunch of r.HandleFunc calls to various endpoints/functions ...

	// api handler
	http.Handle("api", api.Handler())
	http.Handle("/", r)

	// create a logging handler
	h := handlers.LoggingHandler(logFile(), r)

	// wrap with CORS handler
	h = handlers.CORS()(h)

	// return a logging handler
	log.Println("Server now active...")

	return h
}
... HandleFunc targets ...

Then in my daemon, I'm calling:

... snip database setup ...
	// launch http service
	log.Printf("Launching server on http://localhost%v\n", port)
	log.Fatal(http.ListenAndServe(port, mypackage.Handler()))
}

This all still results in github.com/manyminds/api2go/routing/httprouter.go:51: cannot use notAllowedHandler (type http.Handler) as type http.HandlerFunc in assignment: need type assertion message.

@sharpner
Copy link
Member

Yeah... well the fact that NewAPIWithRouting in your example takes four parameters, makes sure that it's an outdated version. You should update to the newest version first, otherwise it's hard to provide any advice that's helpful...

@Linuturk
Copy link
Author

Updated to match your example.

Still running the latest versions based on the dep status from before . . . so I'm not sure how I'm out of date.

github.com/manyminds/api2go          *              0.6            02704db   02704db  3
github.com/manyminds/api2go-adapter  *              branch master  13346ba   13346ba  1

@Linuturk
Copy link
Author

Linuturk commented Oct 13, 2017

Ok, I think I understand now.

It seems that since you used to tag releases, dep picks up on 0.6.0 and uses that by default. I updated my Gopkg.toml to install via the master branch instead of the tag. Now that function takes 3 arguments.

You might want to tag a more recent commit as a newer release. https://github.com/golang/dep

With that in mind, I still had to change a portion of the code.

github.com/manyminds/api2go/routing/httprouter.go line 51 from router.MethodNotAllowed = notAllowedHandler to router.MethodNotAllowed = notAllowedHandler.(http.HandlerFunc)

Do you want a PR to that effect?

@Linuturk
Copy link
Author

Linuturk commented Oct 13, 2017

PR failed miserably in the tests you have setup, so I'm back to not understanding why I'm getting this error. Maybe there's a namespace conflict?

@sharpner
Copy link
Member

The latest Tag is 1.0-RC3 please use that version or master and it will solve your issues.

For proof I just tested a vanilla setup and it works fine:

mkdir tmp && cd tmp
export GOPATH=`pwd`
go get -u -a github.com/manyminds/api2go-adapter/gorillamux
go get -u -a github.com/manyminds/api2go
go run gorilla.go

where as gorilla.go will be one of the snippets above.
It will work :)

@Linuturk
Copy link
Author

package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"

	"github.com/manyminds/api2go"
	"domain.com/user/mypkg"
)

var portFlag = flag.Int(snip)
var cassandraAppFlag = flag.String(snip)
var cassandraKeyspaceFlag = flag.String(snip)

// logPath returns a file hander or os.Stdout based on
// whether this is local dev or deployed in EC2
func logFile() io.Writer {
snip
}

// initDB initializes the database session
func initDB(app, keyspace string) error {
snip
}

func main() {

	// parse flags and set port
	flag.Parse()
	port := fmt.Sprintf(":%v", strconv.Itoa(*portFlag))
	app := *cassandraAppFlag
	keyspace := *cassandraKeyspaceFlag

	// init DB connection
	err := initDB(app, keyspace)
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	// new jsonapi spec
	api := api2go.NewAPI("v2")
	api.AddResource(Device{}, &Device{})
	api.AddResource(Family{}, &Family{})
	api.AddResource(Job{}, &Job{})
	api.AddResource(Sequence{}, &Sequence{})

	// Index, Healthcheck, initDatabase
	r := api.Router()
	r.Handle("GET", "/", mypkg.Index)
	r.Handle("GET", "/healthcheck", mypkg.HealthCheck)
	r.Handle("GET", "/InitDB", mypkg.InitDB)

	// launch http service
	log.Printf("Launching server on http://localhost%v\n", port)
	log.Fatal(http.ListenAndServe(port, api.Handler()))

}

Ripped out all the gorilla mux stuff to simplify things. Still getting the ../vendor/github.com/manyminds/api2go/routing/httprouter.go:51:26: cannot use notAllowedHandler (type http.Handler) as type http.HandlerFunc in assignment: need type assertion error.

Not really sure where to go from here honestly.

@Linuturk Linuturk reopened this Oct 23, 2017
@Linuturk
Copy link
Author

Just as a refresher, here are my current deps in the vendor directory:

[15:52:21] PROJECT                              CONSTRAINT     VERSION        REVISION  LATEST   PKGS USED
[15:52:21] github.com/gedex/inflector           *              branch master  16278e9   16278e9  1  
[15:52:21] github.com/gocql/gocql               branch master  branch master  843f6b1   843f6b1  4  
[15:52:21] github.com/golang/snappy             *              branch master  553a641   553a641  1  
[15:52:21] github.com/hailocab/go-hostpool      *              branch master  e80d13c   e80d13c  1  
[15:52:21] github.com/julienschmidt/httprouter  *              v1.1           8c199fb   8c199fb  1  
[15:52:21] github.com/manyminds/api2go          branch master  branch master  d8e0ec7   d8e0ec7  3  
[15:52:21] gopkg.in/inf.v0                      *              v0.9.0         3887ee9   3887ee9  1  

and my go version

go version go1.9.1 linux/amd64

@Linuturk
Copy link
Author

I just noticed the v1.1 tag on the httprouter package, and pinned to master instead. Problem is gone.

LewisWatson added a commit to LewisWatson/api2go that referenced this issue Nov 1, 2017
LewisWatson added a commit to LewisWatson/api2go-with-gin-example that referenced this issue Nov 9, 2017
In order to use gin with api2go, a build tag is required.
go-dep doesnt support setting build tags in so gin dependencies will
be skipped. Therefore, gin needs to be explicitly listed as a
dependency. This takes us up to [api2go issue #292](manyminds/api2go#292).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants