dqrdlqpo775594 2014-09-11 22:16
浏览 34
已采纳

整理路线和助手

I am starting building a api in go(golang), but I have few questions...

So in my main function or init function(because I might use appengine) I was thinking in calling a function which will define all my routes using gorilla mux. Each pice of my application(post, comments etc...) will have its one package with its structures/methods/functions.

Questions:

  1. Because I was thinking in defining the routes in one function, do I need to import in this file all my packages, to send the requests to the right handlers?

  2. What about helper function, for example I would like to set content type of the response to be application/json for all the handlers where this is necessary, how I will be able to do that?

I'm not looking for frameworks, just some pointer about how can I overcome those questions in golang way.

  • 写回答

1条回答 默认 最新

  • douyouyi8878 2014-09-12 02:21
    关注

    If you define all of the routes in a single function, then the file containing this function will need to import the packages that implement the handlers. The only way to refer to a type or function in another package is to import the package.

    Here's a helper for setting the content type and encoding a value to JSON:

    func JSONHandler(f func(w http.ResponseWriter, r *http.Request) interface{}) http.Handler {
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        v := f(w, r)
        if v != nil {
            w.Header().Set("Content-Type", "application/json")
            if err := json.NewEncoder(w).Encode(v); err != nil {
                log.Println(err)
            }
        }
      })
    }
    

    The argument to this function is a function that returns a value to encode to the response as JSON. For example, this function returns the client's user agent as JSON.

    func UserAgentHandler(w http.ResponseWriter, r *http.Request) interface{} {
      return struct { UserAgent string }{ req.Header.Get("User-Agent") }
    }
    

    Use the following code to register this handler with the Gorilla mux r:

    r.Handle("/user-agent", JSONHandler(UserAgentHandler))
    

    There are many ways to improve JSONHandler.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题