package http_api

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"

    "github.com/julienschmidt/httprouter"
    "github.com/nsqio/nsq/internal/app"
)

type Decorator func(APIHandler) APIHandler

type APIHandler func(http.ResponseWriter, *http.Request, httprouter.Params) (interface{}, error)

type Err struct {
    Code int
    Text string
}

func (e Err) Error() string {
    return e.Text
}

func acceptVersion(req *http.Request) int {
    if req.Header.Get("accept") == "application/vnd.nsq; version=1.0" {
        return 1
    }

    return 0
}

func PlainText(f APIHandler) APIHandler {
    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
        code := 200
        data, err := f(w, req, ps)
        if err != nil {
            code = err.(Err).Code
            data = err.Error()
        }
        switch d := data.(type) {
        case string:
            w.WriteHeader(code)
            io.WriteString(w, d)
        case []byte:
            w.WriteHeader(code)
            w.Write(d)
        default:
            panic(fmt.Sprintf("unknown response type %T", data))
        }
        return nil, nil
    }
}

func NegotiateVersion(f APIHandler) APIHandler {
    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
        data, err := f(w, req, ps)
        if err != nil {
            if acceptVersion(req) == 1 {
                RespondV1(w, err.(Err).Code, err)
            } else {
                // this handler always returns 500 for backwards compatibility
                Respond(w, 500, err.Error(), nil)
            }
            return nil, nil
        }
        if acceptVersion(req) == 1 {
            RespondV1(w, 200, data)
        } else {
            Respond(w, 200, "OK", data)
        }
        return nil, nil
    }
}

func V1(f APIHandler) APIHandler {
    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
        data, err := f(w, req, ps)
        if err != nil {
            RespondV1(w, err.(Err).Code, err)
            return nil, nil
        }
        RespondV1(w, 200, data)
        return nil, nil
    }
}

func Respond(w http.ResponseWriter, statusCode int, statusTxt string, data interface{}) {
    var response []byte
    var err error

    switch data.(type) {
    case string:
        response = []byte(data.(string))
    case []byte:
        response = data.([]byte)
    default:
        w.Header().Set("Content-Type", "application/json; charset=utf-8")
        response, err = json.Marshal(struct {
            StatusCode int         `json:"status_code"`
            StatusTxt  string      `json:"status_txt"`
            Data       interface{} `json:"data"`
        }{
            statusCode,
            statusTxt,
            data,
        })
        if err != nil {
            response = []byte(fmt.Sprintf(`{"status_code":500, "status_txt":"%s", "data":null}`, err))
        }
    }

    w.WriteHeader(statusCode)
    w.Write(response)
}

func RespondV1(w http.ResponseWriter, code int, data interface{}) {
    var response []byte
    var err error
    var isJSON bool

    if code == 200 {
        switch data.(type) {
        case string:
            response = []byte(data.(string))
        case []byte:
            response = data.([]byte)
        case nil:
            response = []byte{}
        default:
            isJSON = true
            response, err = json.Marshal(data)
            if err != nil {
                code = 500
                data = err
            }
        }
    }

    if code != 200 {
        isJSON = true
        response = []byte(fmt.Sprintf(`{"message":"%s"}`, data))
    }

    if isJSON {
        w.Header().Set("Content-Type", "application/json; charset=utf-8")
    }
    w.Header().Set("X-NSQ-Content-Type", "nsq; version=1.0")
    w.WriteHeader(code)
    w.Write(response)
}

func Decorate(f APIHandler, ds ...Decorator) httprouter.Handle {
    decorated := f
    for _, decorate := range ds {
        decorated = decorate(decorated)
    }
    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
        decorated(w, req, ps)
    }
}

func Log(l app.Logger) Decorator {
    return func(f APIHandler) APIHandler {
        return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
            start := time.Now()
            response, err := f(w, req, ps)
            elapsed := time.Since(start)
            status := 200
            if e, ok := err.(Err); ok {
                status = e.Code
            }
            l.Output(2, fmt.Sprintf("%d %s %s (%s) %s",
                status, req.Method, req.URL.RequestURI(), req.RemoteAddr, elapsed))
            return response, err
        }
    }
}

func LogPanicHandler(l app.Logger) func(w http.ResponseWriter, req *http.Request, p interface{}) {
    return func(w http.ResponseWriter, req *http.Request, p interface{}) {
        l.Output(2, fmt.Sprintf("ERROR: panic in HTTP handler - %s", p))
        Decorate(func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
            return nil, Err{500, "INTERNAL_ERROR"}
        }, Log(l), V1)(w, req, nil)
    }
}

func LogNotFoundHandler(l app.Logger) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        Decorate(func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
            return nil, Err{404, "NOT_FOUND"}
        }, Log(l), V1)(w, req, nil)
    })
}

func LogMethodNotAllowedHandler(l app.Logger) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        Decorate(func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
            return nil, Err{405, "METHOD_NOT_ALLOWED"}
        }, Log(l), V1)(w, req, nil)
    })
}

api_response.go的更多相关文章

  1. NSQ之粗读浅谈

    回顾: 以前一直是C++开发(客户端),最近听同事讲go语言不错,随后便决定先从go语法开始投向go的怀抱.由于历史原因学习go语法时,用了半天的时间看完了菜鸟教程上相关资料,后来又看了易百教程上的一 ...

  2. go语言nsq源码解读八 http.go、http_server.go

    这篇讲另两个文件http.go.http_server.go,这两个文件和第六讲go语言nsq源码解读六 tcp.go.tcp_server.go里的两个文件是相对应的.那两个文件用于处理tcp请求, ...

  3. 02: djangorestframework使用

    1.1 djangorestframework登录.认证和权限 1.认证与权限相关模块 # -*- coding: utf-8 -*- from django.utils import six fro ...

  4. 用PHP编写一个APP的API

    第一部分,通信接口的实现 标签(空格分隔): PHP 手机后台 api 通信接口 Andy PHP开发手机API时,一般返回XML或JSON数据类型的数据,除了要返回从源数据(程序本身需要的数据)外还 ...

  5. 在python中配置tornado服务

    import tornado.httpserver import tornado.options import tornado.web from tornado.options import defi ...

  6. api响应类

    接口开发响应类封装 class response{ /* * 封通信接口数据 * @param integer $code 状态码 * @param string $message 状态信息 * @p ...

  7. 如何使用k3OS和Argo进行自动化边缘部署?

    本文转自边缘计算k3s社区 前 言 随着Kubernetes生态系统的发展,新的技术正在被开发出来,以实现更广泛的应用和用例.边缘计算的发展推动了对其中一些技术的需求,以实现将Kubernetes部署 ...

  8. Python+Pytest+Allure+Git+Jenkins接口自动化框架

    Python+Pytest+Allure+Git+Jenkins接口自动化框架 一.接口基础 接口测试是对系统和组件之间的接口进行测试,主要是效验数据的交换,传递和控制管理过程,以及相互逻辑依赖关系. ...

  9. 登录、认证、token处理、前台cookie存储token

    免费课程相关表设计 models的设计 from django.contrib.contenttypes.fields import GenericRelation class Course(mode ...

随机推荐

  1. LeetCode - 二叉树的最大深度

    自己解法,欢迎拍砖 给定一个二叉树,找出其最大深度. 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数. 说明: 叶子节点是指没有子节点的节点. 示例:给定二叉树 [3,9,20,null,nu ...

  2. IIS部署asp.net mvc网站

    iis配置简单的ASP.NET MVC网站编译器:VS 2013本地IIS:IIS 7操作系统:win 7MVC版本:ASP.NET MVC4sql server版本: 2008 r2 打开VS 20 ...

  3. 深入源码解析类Route

    微软官网对这个类的说明是:提供用于定义路由及获取路由相关信息的属性和方法.这个说明已经很简要的说明了这个类的作用,下面我们就从源码的角度来看看这个类的内部是如何工作的. public class Ro ...

  4. MQ队列与哪些机器连接

    1.使用MQ安装用户登录Linux,例如:su - mqm 2.runmqsc Qm1 #Queue 代表要查询的队列3.DISPLAY CONN(*) WHERE(OBJNAME EQ Queue) ...

  5. vncdotool - A command line VNC client

    作者:Daly 出处:http://www.cnblogs.com/daly 欢迎转载,也请保留这段声明.谢谢! 之前的一个项目需要需求希望可以通过命令行去远程执行一些Windows 系统操作. 所以 ...

  6. INCA二次开发-MIP

    1.INCA介绍 INCA是常用的汽车ECU测试和标定的,广泛应用于动力总成等领域.INCA提供了丰富的接口,供用户自动化.定制化.本公众号通过几篇文章,介绍下一些二次开发的方法,本篇介绍MIP. 2 ...

  7. centos6.X安装jdk

    1.查看Linux自带的JDK是否已安装(如果安装则卸载CentOS已安装的低版本) [root@localhost soft]# java -version java version "1 ...

  8. JavaScript之对象继承

    原型链继承 function SuperType(){ this.property = true; } SuperType.prototype.getSuperValue = function(){ ...

  9. php根据地球上任意两点的经纬度计算两点间的距离 原理

    地球是一个近乎标准的椭球体,它的赤道半径为6378.140千米,极半径为6356.755千米,平均半径6371.004千米.如果我们假设地球是一个完美的球体,那么它的半径就是地球的平均半径,记为R.如 ...

  10. LocalDB + IIS

    Win7 + IIS7 1. 安装 (1)LocalDB SQL Express 2012 选中:ENU\x64\SqlLocalDB.MSI (2).net4.5 .net4.5 然后,再配置IIS ...