Import and reuse existing struct from different package - go

I need to import the existing struct from different package that lives in vendor folder. My folder stucture is below
projectname
custom
custom.go
vendor
github.com
somepackage
authentication
models.go
the models.go contains this struct
package authentication
type User struct {
ID int64
AccessToken string
Email string
FullName string
Password string
PasswordHash string
PasswordSalt string
Readonly bool
Role Role
Token string
Username string
}
Now inside my custom/custom.go, I have a function that follows a signature and the code looks like this
Signature
type loginFn func(string, string) (*User, error)
I import like this
import "github.com/somepackage/authentication/models"
func SetupGoGuardian(u, p string) (*User, error) {
But I got error coud not import ...... (no required module provides package)
How to properly import the struct from another package and use it a custom function?

You cannot import files, only packages. Change your import statement to reference the package name:
import "github.com/somepackage/authentication"

Related

Generate Valid Random Faker Values in Go

I am using Validator package. I have the next Struct:
type User struct {
Name string `validate:"required"`
Email string `validate:"required,email"`
CreditCard string `validate:"credit_card"`
Password string `validate:"min=8,max=255"`
}
What can I do to generate valid random values for thats fields?
You can use faker package. It has functions like FirstName(), Email(), CCNumber(). You can also use tags (one, two) with this package in your struct.
If you're writing tests, you can use Fuzzing (implemented in Go 1.18).
Would look like this:
import "testing"
func TestHello(f *testing.F) {
// Add your seeds here
f.add("John", "john#test.com", "1234-5678-1234-5678", "#HelloWorld123")
f.Fuzz(func(t *testing.T, name, email, creditCard, pass string) {
// Write your test here
}))
}
Then run:
$ go test -fuzz

Golang import package remove by vscode

I start to work with go and i am happy :)
But i got a strange problem with package import.
I got a file dto.go :
package dto
import (
"time"
)
type TaskResponse struct {
ID uint `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
A simple response object, but a task have a Status param.
I got a file model.go :
package model
// Status struct
type Status struct {
ID uint
Name string
}
The problem is that i would like to add in TaskResponse the Status object, but when i add this, i got a "undefined Status" and when i force the import of the package vscode remove it automaticly...
Someone know what is my problem ?
Thanks in advance
I found the problem, just need to use model.Status in the object TaskResponse
The reason why this happening is because of what you imported, you didn't use it in the program, so Golang deletes unnecessary dependencies.

Export imports with Golang

Not sure if this is impossible with Golang. With Node.js, I would do it like so:
import * as person from './person';
export {person};
with Golang I have models.go:
package models
import (
"huru/models/person"
)
is it possible to export person from this models.go file, in a person namespace like with TypeScript/node.js?
[I]s it possible to export person from this models.go file, in a person namespace like with TypeScript/node.js?
No.
You cannot just pass through a complete package. You can pass through different types by making your own types based on them. If there was a person.Person:
package models
import (
"huru/models/person"
)
type Person person.Person
//or
type EmbeddedPerson struct{
person.Person
additional string
}
This has the advantage of allowing you to add your own functions
func (p Person) CustomFunc() {}
Here is a playground link that shows some of the nuances of this: https://play.golang.org/p/1aLOcmsXHV2
#MrCholo there is a little difference in golang concept here. The golang structs available under namespace scoped.
Like as per example
package models
// struct name should starts with Capital letter to export
type Person struct {
Name string
age int
}
The Person struct will be available in all files scoped under same namespace(ex. models). You don't need to import that.
But if you would like to access outside the models namespace you'll have to import the package models and access the Person object using that.
ex.
package anotherpackage
import (
"<path to models>/models"
)
var perObj models.Person // here is how you can access the Person struct
Let me know if it's still not clear to you.
No.
You can use like this, for example custom log
package customLog
import "log"
func Print(args ...interface{}) {
log.Print(args)
}
package example
func some() {
customLog.Print("hi babay")
}
Yes, We can export struct from file to another file(or package) like other languages.
person.go
package models
// struct name should starts with Capital letter to export
type Person struct {
Name string
age int
}
If the importing file is in the same package(models), then no need to import. Straight away you can use like this:
details.go
package models
var perObj Person
func abc() {
perObj.Name = "xyz"
}
If the importing file is in some other package, then import models package.
businesslogic.go
package logic
import (
"../../models"
)
var perObj Person
func abc() {
perObj.Name = "xyz"
}

Imported struct to be used as anonymous field

So I'm trying to write a few Go files such that there is a public facing package and an internal package.
In the public facing package, there is a struct that is nearly identical (missing one field) to an internal struct.
I thought of using an anonymous field in the internal struct, but it doesn't seem to play nicely.
Example:
public/public.go:
package public
type PublicStruct struct {
Field1 bool `json:"fetchStats"`
}
data/data.go
package data
import publicData "public"
type InternalStruct struct {
publicData.PublicStruct
Field2 bool `json:"includeHidden:`
}
filter/filter.go:
package filter
import "data"
func test() {
tmp := data.InternalStruct{Field1: true, Field2: false}
}
main.go:
package main
import "filter"
import "data"
func main() {
var tmp data.InternalStruct
tmp.Field1 = true
tmp.Field2 = true
filter.Test()
}
Expected: no issues
Result: filter/filter.go:6: unknown data.InternalStruct field 'Field1' in struct literal
Why does this not work and what should I do to make it work (I'm currently using the duplicate parameters in both structs approach)?
PS: I don't know how to test this in go playground since it involves multiple files.
The issue is that field1 isn't being exported by the public package as it's name is lower cased. If it were instead Field1 then you could access it inside the internal package like MyInternalStructInstance.Field1
EDIT - Addresses OP's update;
The syntax you're using for initilization in your main is just wrong. It should be:
tmp := InternalStruct{PublicStruct: PublicStruct{Field1: true}, Field2: false}
It has nothing to do with the packages or imported vs exported. It can easily be tested on the playground, a complete example is here; https://play.golang.org/p/tbCqFeNStd

Subclassing an object in a different package in golang

I'm trying to create a base object for all my structs in golang. For some reason I can't get it to work when the new object I create is in a different package. It works fine when they are in the same package/folder.
e.g. a base class for all objects
package Test
type BaseObject struct {
base interface{}
}
---- Sub Folder Test\Stuff ---
create a new TestObject which subclasses BaseObject
package Stuff
import Test "Test"
type TestObject struct{
Test.BaseObject
}
func (this *TestObject)DoSomething(){
any reference to this.base or this.BaseObject.base fails!!!
}
--- In the same folder, everthing works ---
package Test
type TestObject struct{
BaseObject
}
func (this *TestObject)DoSomething(){
any reference to this.base works fine??
}
You can't reference hidden or "private" fields in structs outside their packages.
If you would just do:
type BaseObject struct {
Base interface{}
}
Base will be exposed or "public" in the context of other packages, and everything will work.

Resources