Go run server.go why am i getting this error when starting

command-line-arguments

.\server.go:16:2: undefined: AddApproutes
server.go

package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

func main() {

	log.Println("Server will start at http://localhost:8000/")

	route := mux.NewRouter()

	AddApproutes(route)

	log.Fatal(http.ListenAndServe(":8000", route))
}

routes.go

package main

import (
	"log"

	"github.com/gorilla/mux"
)


func AddApproutes(route *mux.Router) {

	log.Println("Loadeding Routes...")

	route.HandleFunc("/", RenderHome)

	route.HandleFunc("/sendEmail", SendEmailHandler).Methods("POST")

	log.Println("Routes are Loaded.")
}

Because there is no AddApproutes defined in server.go. The main package is special, it doesn’t automatically join all files in the same folder. You need to create another package, move that function there, import it from server.go.

As they are in the same package you only need to specify the routes.go file in your run or build command linel, say go run main.go routes.go

I get this error when I add go run main.go routes.go

command-line-arguments

.\routes.go:14:32: undefined: RenderHome
.\routes.go:16:46: undefined: SendEmailHandler

You need to create RenderHome and SendEmailHandler functions. For example

> func RenderHome(w http.ResponseWriter, r *http.Request) {
> 
> w.WriteHeader(http.StatusOK)
> 
> fmt.Fprintf(w, "Hello, World!")
> 
> }
> 
> func SendEmailHandler(w http.ResponseWriter, r *http.Request) {
> 
> }

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.