Can't seem to get started with Go and Echo - go

Trying to build a simple crud api with Golang and Echo and I can't get past the first tep in the Echo docs.
I run go get -u github.com/labstack/echo/...
then I create server.go:
package main
import (
"net/http"
"github.com/labstack/echo/v4"
)
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.Logger.Fatal(e.Start(":1323"))
}
but when I try to run: go run server.go
I get this error:
server.go:6:2: cannot find package "github.com/labstack/echo/v4" in any of:
/usr/local/Cellar/go/1.14.4/libexec/src/github.com/labstack/echo/v4 (from $GOROOT)
/Users/dariusgoore/go/src/github.com/labstack/echo/v4 (from $GOPATH)

You need to enable GO111MODULE. To enable the module you need to run this command.
export GO111MODULE=on
After enabling it when you will run go run server.go then it will install the packages again after that the program will run as expected.

I get the same issue when I run go get before go mod init. Using the following commands, I can run the server successfully:
go mod init example.com/try-echo
go get
go run server.go

I just created a new project with the same main.go and it ran without any issue. I have listed the steps I followed.
package main
import (
"net/http"
"github.com/labstack/echo/v4"
)
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.Logger.Fatal(e.Start(":1323"))
}
and used go.mod for dependencies downloads
go mod init
go get
go run main.go
and it ran without any error
____ __
/ __/___/ / ___
/ _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.1.16
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
O\
⇨ http server started on [::]:1323
I hope this helps. If it doesn't you can run go env and share the result of the command, which will help to debug further.

export GO111MODULE=on
go mod init
go mod tidy
if not succed, add more command:
go mod download

Related

How to Import https://github.com/go-test/deep into Your Golang Test

I'm new to Golang.
My go version: 1.17.8
Trying write tests to compare strcuts.
Found this lib can show you which fields exactly equivalent.
So thought of using it over reflect.DeepEqual
Here's my test go file,
package main
import (
"os"
"testing"
"github.com/go-test/deep"
)
func TestDeepEqual(t *testing.T) {
os.Remove("_decktesting.txt")
d := newDeck()
d.saveToFile("_decktesting.txt")
l := newDeckFromFile("_decktesting.txt")
if diff := deep.Equal(d, l); diff != nil {
t.Error(diff)
}
}
Here's what it says when try to test,
➜ go get
go-training/cards on  develop [!] via 🐹 v1.17.8
➜ go test
# go-training/cards
deck_test.go:7:2: cannot find package "github.com/go-test/deep" in any of:
/usr/local/go/src/github.com/go-test/deep (from $GOROOT)
/Users/ssamarasin/go/src/github.com/go-test/deep (from $GOPATH)
FAIL go-training/cards [setup failed]
go-training/cards on  develop [!] via 🐹 v1.17.8
➜ go install github.com/go-test/deep#latest
package github.com/go-test/deep is not a main package
Can someone please explain how I can use this lib to compare my structs?
Thank you
GO111MODULE=on go get github.com/go-test/deep

go malformed import path empty path element

Trying to run
go mod init `pwd`
On a trivial example
package main
import (
"net/http"
"github.com/labstack/echo/v4"
)
func main() {
// Echo instance
e := echo.New()
// Route => handler
e.GET("/", func(c echo.Context) error {
return c.HTML(http.StatusOK, "Hello, World!\n")
})
// Start server
e.Logger.Fatal(e.Start(":1323"))
}
Gives an error
go malformed import path (path to file) empty path element
Yet if I create a manual go.mod like this
module <path>
go 1.12
require github.com/labstack/echo/v4 v4.1.6
Then I can build / run the code normally.
Any idea why go mod init fails?
Mostly for future reference as creating the go.mod solves the immediate issue.
Try initializing the modules in the console. The syntax for that is go mod init <mod_name> where mod_name can be github.com/labstack/echo/v4.
As suggested above, go mod init but without / at the beginning of your path works. Perhaps outside of GOPATH relative paths should be used instead of absolute paths(?)

dlv debug fail due to undefined object in same package

I filed a bug for this over at the delve site.
So, to explain what's going on. I have 2 files in the same package, main.go and common.go. In main.go, it uses some structure from common.go and when i run
dlv debug --listen=:2345 --headless --api-version=2 --log main.go
it fails with 'undefined: NewSimpleStruct' and i am not sure what i am doing wrong.
Here's what the Go files contain,
//main.go
package main
import (
"fmt"
)
func main() {
fmt.Println("HELLO WORLD!")
segasaturn := NewSimpleStruct("SS", 69)
segasaturn.WhoAmI()
fmt.Println("BYE WORLD!")
}
//common.go
package main
import "fmt"
type simpleStruct struct {
name string
id int
}
func NewSimpleStruct(name string, id int) *simpleStruct {
return &simpleStruct{name, id}
}
func (ss *simpleStruct) WhoAmI() {
fmt.Printf("name: %s, id: %d\n", ss.name, ss.id)
}
You did not list the second source file common.go by name.
So try:
dlv debug --listen=:2345 --headless --api-version=2 --log main.go common.go
A common error, and it's not delve's fault; note that you also can't go build main.go here.
You need to do go build . or go build main.go common.go.
Similarly just put all the files or a dot(.) instead of main.go to include all the .go files in the directory
dlv debug --listen=:2345 --headless --api-version=2 --log .

My main.go file cannot see other files

I need some help understanding what is wrong with my file layout in a simple web application.
$GOPATH/src/example.com/myweb
I then have 2 files:
$GOPATH/src/example.com/myweb/main.go
$GOPATH/src/example.com/myweb/api.go
Both files have:
package main
The api.go file looks like:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type API struct {
URI string
Token string
Secret string
client *http.Client
}
...
My main.go file looks like:
package main
import (
"github.com/gorilla/mux"
"html/template"
"net/http"
)
var (
templates = template.Must(template.ParseFiles("views/home.html", "views/history.html", "views/incident.html"))
api = API{
URI: "http://localhost:3000",
Token: "abc",
Secret: "123",
}
)
func renderTemplate(w http.ResponseWriter, tmpl string, hp *HomePage) {
..
..
}
func WelcomeHandler(w http.ResponseWriter, r *http.Request) {
..
..
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", WelcomeHandler)
r.PathPrefix("/assets/").Handler(
http.StripPrefix("/assets/", http.FileServer(http.Dir("assets/"))))
http.ListenAndServe(":9000", r)
}
In the code I excluded, I basically use structs that are defined in my api.go file, and I get this error when doing:
go run main.go
# command-line-arguments
./main.go:16: undefined: API
./main.go:23: undefined: User
What exactly am I doing wrong here?
I tried changing the package name in api.go to myweb but that didn't help.
Am I suppose to use the package name myweb? Is just 1 file suppose to have main?
You're compiling only the main.go file. You should use:
go run main.go api.go
Or:
go run *.go
If you're writing a complex application, you might add everything to packages in subdirectories and have a single main.go file. For instance, etcd has an etcdmain subdirectory/package along with other subdirectories/packages. Something like:
/alarm
/auth
/cmd
/etcdmain
...
And the main.go file is simply:
package main
import "github.com/coreos/etcd/etcdmain"
func main() {
etcdmain.Main()
}
You are using golang workspace project, which is good for the structure for your application and it also standardize.
When we use the golang workspace, you can not run single go file. You need to call go build / go install.
Install
go install example.com/myweb
The command above will compile your main package on example.com/myweb. And the myweb executable binary will be placed on the GOPATH/bin. And you can run it manually.
Build
go build example.com/myweb
The command is similar to go install but the binary executable file will be placed on the current directory when you call the command, instead of on GOPATH/bin (unless your current directory is GOPATH/bin).
For more information please check this link.

Golang on OpenShift, I can't find local module

I want to use an OpenShift test environment for my Golang applications.
I made a test application:
myproj/
------web.go
------/mylib/
-------------mylib.go
web.go is standard OpenShift file:
package main
import (
"fmt"
"net/http"
"os"
"runtime"
"./mylib"
)
func main() {
http.HandleFunc("/", hello)
bind := fmt.Sprintf("%s:%s", os.Getenv("HOST"), os.Getenv("PORT"))
fmt.Printf("listening on %s...", bind)
err := http.ListenAndServe(bind, nil)
if err != nil {
panic(err)
}
}
func hello(res http.ResponseWriter, req *http.Request) {
str := mylib.Lib();
fmt.Fprintf(res, "hello, %s from %s", str, runtime.Version())
}
and I created "mylib"
package mylib
func Lib() string {
return "world"
}
and when I run "go run web.go" everything works fine on my local computer. But when I try to upload this code to OpenShift I get the following error:
remote: -----> Using Go 1.1.2
remote: -----> Running: go get -tags openshift ./...
remote: can't load package: /var/lib/openshift/5354e6fd4382ec2dca000223/app-root/runtime/repo/.openshift/g/src/github.com/smarterclayton/goexample/web.go:8:2: local import "./mylib" in non-local package
remote: An error occurred executing 'gear postreceive' (exit code: 1)
remote: Error message: CLIENT_ERROR: Failed to execute: 'control build' for /var/lib/openshift/5354e6fd4382ec2dca000223/go
What does this mean? Why can't Golang find this package? I can't write all code in one file. How should I write the application for OpenShift?
I know this question is old but i had the same problem and it was difficult to find the solution, so i decided to ask in order to help who will run on the same problem.
The solution is very simple and can be found in readme of the go cartdrige repo on github: github.com/smarterclayton/openshift-go-cart
You have to create a file named .godir and put here the name of the main package of your server.
For example if you put myserver you can use:
package main
import "myserver/mylib"
func main() {
mylib.DoStuff()
}
Basically when you push on openshift the repo is copied in the directory placed in .godir before the build

Resources