在解组字段的JSON内容时打印结构字段标签?

In Go, Is it possible to get the tags from a struct field while I'm unmarshaling JSON content to it? Here's my failed attempt at doing so:

package main
import (
  "log"
  "encoding/json"
)
type Person struct {
  ProfileName AltField `json:"profile_name"`
}

type AltField struct {
  Val string
}

func (af *AltField) UnmarshalJSON(b []byte) error {
  log.Println("Show tags")
  //log.Println(af.Tag) // I want to see `json:"profile_name"`
  if e := json.Unmarshal(b,&af.Val); e != nil {
    return e
  }
  return nil
}
func main() {
  p := Person{}
  _ = json.Unmarshal([]byte(`{"profile_name":"Af"}`),&p)

}

I commented out the line log.Println(af.Tag) because it causes compilation errors. If I can get a handle on the tags from the Person struct, that will allow me to develop some other conditional logic.

Is this possible?

Use reflection to get the value of struct field tag. The reflect package provides functions to work with tags including to get the value of tag

package main

import (
  "log"
  "encoding/json"
  "reflect"
)
type Person struct {
  ProfileName AltField `json:"profile_name"`
}

type AltField struct {
  Val string `json:"val"`
}

func (af *AltField) UnmarshalJSON(b []byte) error {
  field, ok := reflect.TypeOf(*af).FieldByName("Val")
  if !ok {
    panic("Field not found")
  }
  log.Println(string(field.Tag))

  if e := json.Unmarshal(b,&af.Val); e != nil {
    return e
  }
  return nil
}

func main() {
  p := Person{}
  _ = json.Unmarshal([]byte(`{"profile_name":"Af"}`),&p)

}

You can only get the value of those field tags which has them. The struct field reflect object should be created for fetching the tags of its fields.

Working Code on Playground