Use same package function with Golang

Asked

Viewed 233 times

1

Within my project I have 2 files, main.go and price.go; in my file main.go within the function main() i tried calling a file function price which is exportable (starts with uppercase letter), and when trying to execute I get the error that the function was not defined;

./main.go:13:30: United States: 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?

  • 1

    I don’t see any problem, you’re using the go run? Use the go build or go run *.go.

  • @Inkeliz the problem was run as you commented, I was running only go run main.go, when I executed go run *.go worked. Please put as answer so I can mark as solved.

1 answer

1

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

There are some ways to fix:

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

Note that using dependencies/packages, even if they have more than one file, will work normally when using go run. So the import no problem, except if an invalid GOPATH is configured.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.