Use function from the same package with Golang

1

Within my project I have 2 files, main.go and price.go ; in my main.go file inside the main() function I tried to call a function from the price file that is exportable (starts with a capital letter), and when trying to execute I get the error that the function was not defined; >

  

./ main.go: 13: 30: undefined: GetPrice

Code:

main.go:

package main

import ( ... )

func main() {
    router := mux.NewRouter()

    // Router registry for "/price" endpoint
    router.HandleFunc("/price", GetPrice).Methods("POST")

    http.ListenAndServe(":8080", router)
}

price.go:

package main

import (...)

// Price represent all fields in prices request
type Price struct {
    SKU       string  'json:"sku"'
    SellerID  string  'json:"seller_id"'
}

// GetPrice retrieve a json response to requested price
func GetPrice(writter http.ResponseWriter, request *http.Request) {
    fmt.Println("Hello! GET PRICE!")
}

Even declaring an "exportable" function because I keep getting this error?

    
asked by anonymous 19.05.2018 / 21:22

1 answer

1

The go run will only execute the file you mention, for example go run main.go . If the code is spread over multiple files it will not be read, which makes the function non-existent.

There are a few ways to fix:

  • go run main.go price.go : Will run both files.
  • go run *.go : Will run all files in the same directory.
  • go build : Will compile files from the same directory, but will not run when finished.

Note that using dependencies / packages, even if they have more than one file, will work normally when using go run . So, import is not a problem, unless an Invalid GOPATH is set up.

    
21.05.2018 / 15:55