Go structure encapsulation

I am new to Go. I read that encapsulation in Go is at the package level. I have a simple example of using a web controller. I have a struct that comes in as a JSON object and is not bound to a structure type.

type User struct{
    Name String `json:"name"`
    //Other Variables
}

Now json can be decoupled to type User Struct by json.Unmarshal ([] byte). However, this user structure is also available for other packages. How can I make sure that other methods related to the user are available for other packages.

One solution I could think of:

type User struct{
    name String
}

type UserJSON struct{
    Name String `json:"name"`
}

func DecodeJSONToUser(rawJSON []byte) (User,error) {
    var userJSON UserJSON
    err := json.Unmarshal(rawJSON,&userJSON)
    //Do error handling
    return User{name:userJSON.Name},nil
}

Is there a GOish way to achieve this?

+4
source share
1 answer

, . , :

package user

import "encoding/json"

type User interface {
    Name() string
}

type user struct {
    Username string `json:"name"`
}

func (u *user) Name() string {
    return "Mr. " + u.Username
}

func ParseUserData(data []byte) (User, error) {
    user := &user{}
    if err := json.Unmarshal(data, user); err != nil {
        return nil, err
    }
    return user, nil
}

:

package user_test

import (
    "testing"

    "github.com/teris-io/user"
)

func TestParseUserData(t *testing.T) {
    data := []byte("{\"name\": \"Uncle Sam\"}")
    expected := "Mr. Uncle Sam"
    if usr, err := user.ParseUserData(data); err != nil {
        t.Fatal(err.Error())
    } else if usr.Name() != expected {
        t.Fatalf("expected %s, found %s", expected, usr.Name())
    }
}

➜ git:( ) ✗ go test github.com/teris-io/user

ok github.com/teris-io/user 0.001s

- .

. , , - ( user.Name user.Name ) name. , : JSON, .

+8

Source: https://habr.com/ru/post/1694513/


All Articles