golang Go的反思例子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang Go的反思例子相关的知识,希望对你有一定的参考价值。

package main

import(
  "fmt"
  "reflect"
)

func main(){
  // iterate through the attributes of a Data Model instance
  for name, mtype := range attributes(&Dish{}) {
    fmt.Printf("Name: %s, Type %s\n", name, mtype.Name())
  }
}

// Data Model
type Dish struct {
  Id  int
  Name string
  Origin string
  Query func()
}

// Example of how to use Go's reflection
// Print the attributes of a Data Model
func attributes(m interface{}) (map[string]reflect.Type) {
  typ := reflect.TypeOf(m)
  // if a pointer to a struct is passed, get the type of the dereferenced object
  if typ.Kind() == reflect.Ptr{
    typ = typ.Elem()
  }
  
  // create an attribute data structure as a map of types keyed by a string.
  attrs := make(map[string]reflect.Type)
  // Only structs are supported so return an empty result if the passed object
  // isn't a struct
  if typ.Kind() != reflect.Struct {
    fmt.Printf("%v type can't have attributes inspected\n", typ.Kind())
    return attrs
  }

  // loop through the struct's fields and set the map
  for i := 0; i < typ.NumField(); i++ {
    p := typ.Field(i)
      if !p.Anonymous {
        attrs[p.Name] = p.Type
      }
     }

  return attrs
}

golang 使用Martini和Redigo在Go中编写的一个小例子API

package main

import (
	"flag"
	"fmt"
	"net/http"

	"github.com/codegangsta/martini"
	"github.com/garyburd/redigo/redis"
	"github.com/martini-contrib/render"
)

var (
	redisAddress   = flag.String("redis-address", ":6379", "Address to the Redis server")
	maxConnections = flag.Int("max-connections", 10, "Max connections to Redis")
)

func main() {
	martini.Env = martini.Prod

	flag.Parse()

	redisPool := redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", *redisAddress)

		if err != nil {
			return nil, err
		}

		return c, err
	}, *maxConnections)

	defer redisPool.Close()

	m := martini.Classic()

	m.Map(redisPool)

	m.Use(render.Renderer())

	m.Get("/", func() string {
		return "Hello from Martini!"
	})

	m.Get("/set/:key", func(r render.Render, pool *redis.Pool, params martini.Params, req *http.Request) {
		key := params["key"]
		value := req.URL.Query().Get("value")

		c := pool.Get()
		defer c.Close()

		status, err := c.Do("SET", key, value)

		if err != nil {
			message := fmt.Sprintf("Could not SET %s:%s", key, value)

			r.JSON(400, map[string]interface{}{
				"status":  "ERR",
				"message": message})
		} else {
			r.JSON(200, map[string]interface{}{
				"status": status})
		}
	})

	m.Get("/get/:key", func(r render.Render, pool *redis.Pool, params martini.Params) {
		key := params["key"]

		c := pool.Get()
		defer c.Close()

		value, err := redis.String(c.Do("GET", key))

		if err != nil {
			message := fmt.Sprintf("Could not GET %s", key)

			r.JSON(400, map[string]interface{}{
				"status":  "ERR",
				"message": message})
		} else {
			r.JSON(200, map[string]interface{}{
				"status": "OK",
				"value":  value})
		}
	})

	m.Run()
}

以上是关于golang Go的反思例子的主要内容,如果未能解决你的问题,请参考以下文章

golang 使用Martini和Redigo在Go中编写的一个小例子API

golang 条件编译

golang Golang反思范例

实例新类型(Golang)

编写一个go gRPC的服务

Golang——详解Go语言代码规范