I am using etcd's wal package (https://godoc.org/github.com/coreos/etcd/wal) to do write-ahead logging. wal has go.uber.org/zap in its vendor packages. In wal's create function func Create(lg *zap.Logger, dirpath string, metadata []byte) (*WAL, error), I need to pass in zap.Logger.
I have tried to import go.uber.org/zap but go compiler complains "type mismatch" when I pass in zap.Logger.
package main
import (
"github.com/coreos/etcd/wal"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
metadata := []byte{}
w, err := wal.Create(zap.NewExample(), "/tmp/hello", metadata)
// err := w.Save(s, ents)
}
How should I use zap.Logger in my project?
It seems like the package github.com/coreos/etcd/wal is not meant to be used outside of the etcd project. If you really need to use it, please, follow the steps below.
Place the following code in the $GOPATH/src/yourpackage/main.go file.
package main
import (
"fmt"
"go.etcd.io/etcd/wal"
"go.uber.org/zap"
)
func main() {
metadata := []byte{}
w, err := wal.Create(zap.NewExample(), "/tmp/hello", metadata)
fmt.Println(w, err)
}
mkdir $GOPATH/src/yourpackage/vendor
cp -r $GOPATH/src/go.etcd.io $GOPATH/src/yourpackage/vendor/
mv $GOPATH/src/yourpackage/vendor/go.etcd.io/etcd/vendor/go.uber.org $GOPATH/src/yourpackage/vendor/
go build yourpackage
Related
I am trying to use Go api-call function in javascript by converting the Go function into web assembly. To do that I am trying to import syscall/js but it throws the following error:
imports syscall/js: build constraints exclude all Go files in /usr/local/go/src/syscall/js
package main
import (
"fmt"
"io/ioutil"
"net/http"
"syscall/js" // I can't use syscall/js
)
func main() {
fmt.Println("Go Web Assembly")
js.Global().Set("getData", getData)
}
func getData(string, error) {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
return
}
// We Read the response body on the line below.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
// Convert the body to type string
sb := string(body)
return sb
}
The syscall/js package has indeed a build constraint:
// +build js,wasm
You need to build the program with the correct GOOS and GOARCH options:
GOOS=js GOARCH=wasm go build -o main.wasm
I'm trying to write a service in go with gRPC, and when i import the protobuff file , getting an error. i tried removing all the modules in my go path and reinitialising the go modules
build _/Users/tibinlukose/cart-service/pb: cannot find module for path _/Users/tibinlukose/cart-service/pb
Code
package main
import (
pbcart "../pb/"
"log"
"fmt"
"google.golang.org/grpc"
"net"
)
var (
port = 1000;
)
type CartServiceServer struct {
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
fmt.Println("Server Starting ..")
lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", 10000))
if err != nil {
log.Fatal("unable to listen on the port")
}
serverOptions := []grpc.ServerOption{}
grpcServer := grpc.NewServer(serverOptions...)
srv := &CartServiceServer{}
pbcart.RegisterCartServiceServer(grpcServer, srv)
}
env
GOCACHE="/Users/tibinlukose/Library/Caches/go-build"
GOENV="/Users/tibinlukose/Library/Application Support/go/env"
GOPATH="/Users/tibinlukose/go"
GOROOT="/usr/local/Cellar/go/1.13.4/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.13.4/libexec/pkg/tool/darwin_amd64"
GOMOD="/Users/tibinlukose/cart-service/server/go.mod"
repo https://github.com/zycon/cart-service
Move your go.mod to the root and update import to github.com/zycon/cart-service/pb?
There is no relative import in Go. You can see this answer for an extended explanation: Relative imports in Go
There is a proposal: https://github.com/golang/go/issues/20883
I'm having difficulty when trying to get path of imported package. When I print result of os.Getwd() inside imported package, it's showing same path like on main package.
This what I did.
Project structure
lib/lib.go
package lib
import "os"
import "fmt"
func init() {
dir, _ := os.Getwd()
fmt.Println("lib.init() :", dir)
}
func GetPath() {
dir, _ := os.Getwd()
fmt.Println("lib.GetPath() :", dir)
}
main.go
package main
import "os"
import "fmt"
import "test-import/lib"
func main() {
dir, _ := os.Getwd()
fmt.Println("main :", dir)
lib.GetPath()
}
Result
lib.init() : /Users/novalagung/Documents/go/src/test-import
main : /Users/novalagung/Documents/go/src/test-import
lib.GetPath() : /Users/novalagung/Documents/go/src/test-import
The result of os.Getwd() from lib/lib.go is still same path like on main. What I want is the real path of the package which is /Users/novalagung/Documents/go/src/test-import/lib/
What should I do? Is it possible?
If you can get a reference to something in the package, you can use reflect to get the import path.
Here's an example on Play:
package main
import (
"bytes"
"fmt"
"reflect"
)
func main() {
var b bytes.Buffer
fmt.Println(reflect.TypeOf(b).PkgPath())
}
PkgPath() only can retrieve the package path for non-pointer
// If the type was predeclared (string, error) or not defined (*T, struct{},
// []int, or A where A is an alias for a non-defined type), the package path
// will be the empty string.
func packageName(v interface{}) string {
if v == nil {
return ""
}
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
return val.Elem().Type().PkgPath()
}
return val.Type().PkgPath()
}
I have a project using Go module, and the content of go.mod is
module github.com/xxx/yyy
Then, I create a sub directory log and a source file log.go, the project structure looks like this:
yyy
- go.mod
- main.go
- log
- log.go
Then I write the code in main.go
import (
"github.com/xxx/yyy/log"
"go/ast"
"go/build"
"go/importer"
"go/parser"
"go/token"
"go/types"
)
var fileSet = token.NewFileSet()
func main() {
file, err := parser.ParseFile(fileSet, "main", nil, parser.ParseComments)
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check(".", fileSet, []*ast.File{file}, nil)
if err != nil {
log.Log.Fatal(err.Error()) // type error
}
}
Then I build it successfully, but when I run it, it crashes and logs could not import github.com/xxx/yyy/log. The err comes from conf.Check definitely, but why does it crash? Does go/types not support go module?
I'm trying to build a Go project using the layout as described in Go Project Layout
I'm using go 1.9.2 on Ubuntu. My project layout is as follows
$GOPATH/src/github.com/ayubmalik/cleanprops
/cmd
/cleanprops
/main.go
/internal
/pkg
/readprops.go
The file cmd/cleanprops/main.go is referring to the cleanprops package i.e.
package main
import (
"fmt"
"github.com/ayubmalik/cleanprops"
)
func main() {
body := cleanprops.ReadProps("/tmp/hello.props")
fmt.Println("%s", body)
}
The contents of internal/pkg/readprops.go are:
package cleanprops
import (
"fmt"
"io/ioutil"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func ReadProps(file string) string {
body, err := ioutil.ReadFile(file)
check(err)
fmt.Println(string(body))
return body
}
However when I build cmd/cleanprops/main.go, from inside directory $GOPATH/src/github.com/ayubmalik/cleanprops, using command:
go build cmd/cleanprops/main.go
I get the following error:
cmd/cleanprops/main.go:5:2: no Go files in /home/xyz/go/src/github.com/ayubmalik/cleanprops
What am I missing?
The document suggests this structure:
$GOPATH/src/github.com/ayubmalik/cleanprops
/cmd
/cleanprops
/main.go
/internal
/pkg
/cleanprops
/readprops.go
Import the package like this. The import path matches the directory structure below $GOPATH/src.
package main
import (
"fmt"
"github.com/ayubmalik/cleanprops/internal/pkg/cleanprops"
)
func main() {
body := cleanprops.ReadProps("/tmp/hello.props")
fmt.Println("%s", body)
}