Created
August 28, 2021 02:20
-
-
Save aloftin/9491e089a5aa413fad0c2f0070ee284d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "reflect" | |
| ) | |
| // Name of the struct tag used in examples | |
| const tagName = "phi" | |
| type UserResponse struct { | |
| Id int `json:"id"` | |
| Name string `json:"name"` | |
| Email string `json:"email"` | |
| SSN string `json:"ssn"` | |
| } | |
| type UsersResponse struct { | |
| Users []UserResponse | |
| } | |
| func (r UsersResponse) FromUsers(users []User) UsersResponse { | |
| for _, u := range users { | |
| maskPHI(u) // masking underlying values on the User | |
| ur := UserResponse{ | |
| Id: u.Id, | |
| Name: u.Name, | |
| Email: u.Email, | |
| SSN: u.SSN, | |
| } | |
| r.Users = append(r.Users, ur) | |
| } | |
| return r | |
| } | |
| type User struct { | |
| Id int | |
| Name string | |
| Email string | |
| SSN string `phi:"XXX-XX-XXXX"` | |
| } | |
| func GetUsers() []User { | |
| users := []User{ | |
| {Id: 1, Name: "John Smith", Email: "jsmith@test.com", SSN: "987-65-4321"}, | |
| {Id: 2, Name: "Jane Doe", Email: "jdoe@test.com", SSN: "123-45-6789"}, | |
| } | |
| return users | |
| } | |
| func maskPHI(s interface{}) { | |
| t := reflect.TypeOf(s) | |
| mutable := reflect.ValueOf(&s).Elem() | |
| // Iterate over all available fields and read the tag value | |
| for i := 0; i < t.NumField(); i++ { | |
| field := t.Field(i) | |
| tag := field.Tag.Get(tagName) | |
| if tag != "" { | |
| // Overwrite the field value with the tag value | |
| f := mutable.FieldByName(field.Name) | |
| f.SetString(tag) | |
| } | |
| } | |
| } | |
| func main() { | |
| users := GetUsers() | |
| res := UsersResponse{}.FromUsers(users) | |
| fmt.Println(res) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment